【问题标题】:Pandas: How to draw bar graph on month over counts熊猫:如何在月数上绘制条形图
【发布时间】:2021-06-07 01:20:42
【问题描述】:
我有一个数据框df 如下:
Student_id Date_of_visit(d/m/y)
1 1/4/2020
1 30/12/2019
1 26/12/2019
2 3/1/2021
2 10/1/2021
3 4/5/2020
3 22/8/2020
如何获得以x-axis 为月-年的条形图(例如:y-ticks:2019 年 12 月、2020 年 1 月、2020 年 2 月)和y-axis - 访问的学生总数(计数)在特定月份。
【问题讨论】:
标签:
python
python-3.x
pandas
matplotlib
seaborn
【解决方案1】:
将值转换为日期时间,然后使用DataFrame.resample 和Resampler.size 进行计数,通过DatetimeIndex.strftime 创建新的日期时间格式:
df['Date_of_visit'] = pd.to_datetime(df['Date_of_visit'], dayfirst=True)
s = df.resample('M', on='Date_of_visit')['Student_id'].size()
s.index = s.index.strftime('%b %Y')
print (s)
Date_of_visit
Dec 2019 2
Jan 2020 0
Feb 2020 0
Mar 2020 0
Apr 2020 1
May 2020 1
Jun 2020 0
Jul 2020 0
Aug 2020 1
Sep 2020 0
Oct 2020 0
Nov 2020 0
Dec 2020 0
Jan 2021 2
Name: Student_id, dtype: int64
如果只需要计数唯一的Student_id,请使用Resampler.nunique:
s = df.resample('M', on='Date_of_visit')['Student_id'].nunique()
s.index = s.index.strftime('%b %Y')
print (s)
Date_of_visit
Dec 2019 1
Jan 2020 0
Feb 2020 0
Mar 2020 0
Apr 2020 1
May 2020 1
Jun 2020 0
Jul 2020 0
Aug 2020 1
Sep 2020 0
Oct 2020 0
Nov 2020 0
Dec 2020 0
Jan 2021 1
Name: Student_id, dtype: int64
Series.plot.bar的最后一张图
s.plot.bar()