[英]pandas dataframe groupby datetime month
考虑一个 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
但是,我似乎无法找到按月合并的功能。
设法做到了:
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+
(更新:2018)
请注意, pd.Timegrouper
已折旧并将被删除。 改用:
df.groupby(pd.Grouper(freq='M'))
避免 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
, pd.Grouper 确实支持convention
参数,但这仅适用于PeriodIndex
石斑鱼。
上述想法的替代方法是转换为字符串,例如将 datetime 2017-10-XX
转换为字符串'2017-10'
。 但是,不建议这样做,因为与字符串object
系列(存储为指针数组)相比, datetime
序列(在内部存储为连续内存块中的数字数据)的所有效率优势都将丢失。
@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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.