简体   繁体   English

按月绘制条形图-Matplotlib

[英]Plotting bar graph by month - matplotlib

I have a dataset that is in the following form: 我有以下形式的数据集:

Date        A   B   C
01/04/2012  2   5   Y
05/04/2012  3   4   Y
06/05/2012  7   6   Y
09/05/2012  8   2   N
11/05/2012  1   4   Y
15/06/2012  5   4   Y

That continues on with more rows. 继续增加行。

I want to plot a bar chart with date on the bottom axis converted to show just the month (ie April, May, July) and then on the y-axis I want the average of the sum of the A and B column so for the month of April it would be 7 (14 total over two instances) and for May it would be 9.33 (28 total over 3 instances). 我想绘制一个条形图,底部轴上的日期转换为仅显示月份(即4月,5月,7月),然后在y轴上,我想要A和B列的总和的平均值,因此对于4月为7(两个实例总共14个),5月为9.33(3个实例总共28)。

I'm really struggling with how to do this and I'd prefer not to create another column that sums up A and B. 我真的在如何做到这一点上挣扎,我不希望不要创建另一个总结A和B的列。

You can use groupby on month_name then mean + eval : 您可以在month_name上使用groupby ,然后mean + eval

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
df.groupby([df['Date'].dt.month_name()], sort=False).mean().eval('A+B')\
  .plot(kind='bar')

在此处输入图片说明


print(df.groupby([df['Date'].dt.month_name()], sort=False).mean().eval('A+B'))
Date
April    7.000000
May      9.333333
June     9.000000
dtype: float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM