Pandas 数据框按日期时间月份分组
- 2025-03-05 09:16:00
- admin 原创
- 67
问题描述:
考虑一个 CSV 文件:
string,date,number
a string,2/5/11 9:16am,1.0
a string,3/5/11 10:44pm,2.0
a string,4/22/11 12:07pm,3.0
a string,4/22/11 12:10pm,4.0
a string,4/29/11 11:59am,1.0
a string,5/2/11 1:41pm,2.0
a string,5/2/11 2:02pm,3.0
a string,5/2/11 2:56pm,4.0
a string,5/2/11 3:00pm,5.0
a string,5/2/14 3:02pm,6.0
a string,5/2/14 3:18pm,7.0
我可以读入它,并将日期列重新格式化为日期时间格式:
b = pd.read_csv('b.dat')
b['date'] = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
我一直在尝试按月份对数据进行分组。似乎应该有一种明显的方法来访问月份并按月份分组。但我似乎做不到。有人知道怎么做吗?
我目前正在尝试按日期重新编制索引:
b.index = b['date']
我可以像这样访问月份:
b.index.month
然而我似乎找不到按月汇总的功能。
解决方案 1:
成功做到了:
b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])
或者
b.groupby(pd.Grouper(freq='M')) # update for v0.21+
解决方案 2:
(更新:2018 年)
请注意pd.Timegrouper
已贬值并将被删除。请改用:
df.groupby(pd.Grouper(freq='M'))
解决方案 3:
要按时间序列数据进行分组,可以使用方法resample
。例如,按月份分组:
df.resample(rule='M', on='date')['Values'].sum()
您可以在此处找到带有偏移别名的列表。
解决方案 4:
避免 MultiIndex 的一个解决方案是创建一个新datetime
列设置 day = 1。然后按此列分组。
标准化月份日期
df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
'Values': [5, 10, 15, 20]})
# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)
然后groupby
正常使用:
g = df.groupby('YearMonth')
res = g['Values'].sum()
# YearMonth
# 2017-09-01 20
# 2017-10-01 30
# Name: Values, dtype: int64
比较pd.Grouper
这种解决方案的微妙好处是,与不同pd.Grouper
,石斑鱼指数被标准化为每个月的开始get_group
而不是结束,因此您可以通过以下方式轻松提取组:
some_group = g.get_group('2017-10-01')
计算十月的最后一天稍微麻烦一些。pd.Grouper
从 v0.23 开始,确实支持convention
参数,但这仅适用于PeriodIndex
石斑鱼。
与字符串转换的比较
上述想法的替代方法是转换为字符串,例如将 datetime 转换2017-10-XX
为 string '2017-10'
。但是,不建议这样做,因为与一系列字符串(存储为指针数组)datetime
相比,您会失去一系列(在内部以数值形式存储在连续内存块中)的所有效率优势object
。
解决方案 5:
与@jpp 的解决方案略有不同,但输出一个YearMonth
字符串:
df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))
res = df.groupby('YearMonth')['Values'].sum()
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD