Groupby在pandas的帮助下使用seaborn或plotly在python中创建两个折线图

2024-05-19 11:31:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,如下所示。这是2016年12月至2018年11月两种保健产品的销售数据

product     price      sale_date       discount
   A         50         2016-12-01      5
   A         50         2017-01-03      4
   B         200        2016-12-24      10
   A         50         2017-01-18      3
   B         200        2017-01-28      15
   A         50         2017-01-18      6
   B         200        2017-01-28      20
   A         50         2017-04-18      6
   B         200        2017-12-08      25
   A         50         2017-11-18      6
   B         200        2017-08-21      20
   B         200        2017-12-28      30
   A         50         2018-03-18      10
   B         300        2018-06-08      45
   B         300        2018-09-20      50
   A         50         2018-11-18      8
   B         300        2018-11-28      35

根据以上数据,我想在一个条形图中为python中使用的每个产品绘制月份的总销售价格和总折扣

所以我想要两个产品A的直线图

X axis = year and month
Y axis1 = Total sale price
Y axis = Total discount price

此图的目的是影响折扣对销售的影响


Tags: 数据date产品绘制discountsaleproductprice
2条回答

试着这样做:

df["sale_date"] = pd.to_datetime(df["sale_date"])
df.set_index("sale_date", inplace=True)

new_df = df.groupby(pd.Grouper(freq='M')).apply(lambda x: x.groupby(by="product")[["price","discount"]].sum()).unstack()

#convert datetime to month-year format
new_df.index = pd.Series(new_df.index).dt.strftime('%b-%Y')

new_df.plot(kind="bar", figsize=(10,7))

条形图:

enter image description here

如果需要堆叠的绘图,请将stacked = True添加到plot

df['sale_date']=pd.to_datetime(df['sale_date']).dt.to_period('M')#Coerce date to datetime Month Year
df.set_index(df['sale_date'], inplace=True)#Set date as index



 df2=df[df['product']=='A']#Boolean select product A
 df2.groupby(df2.index).agg(PriceSum=('price','sum'), DiscountSum=('discount','sum')).plot(legend=True)#Groupby index and plot

enter image description here

相关问题 更多 >

    热门问题