【发布时间】:2017-12-22 16:51:22
【问题描述】:
我经常使用Pandas,它很棒。我也使用TimeGrouper,它很棒。我实际上不知道关于TimeGrouper 的文档在哪里。有吗?
谢谢!
【问题讨论】:
我经常使用Pandas,它很棒。我也使用TimeGrouper,它很棒。我实际上不知道关于TimeGrouper 的文档在哪里。有吗?
谢谢!
【问题讨论】:
pd.TimeGrouper() 在 pandas v0.21.0 中是 formally deprecated,支持 pd.Grouper()。
pd.Grouper() 的最佳用途是在groupby() 内,当您还对非日期时间列进行分组时。如果您只需要按频率分组,请使用resample()。
例如,假设您有:
>>> import pandas as pd
>>> import numpy as np
>>> np.random.seed(444)
>>> df = pd.DataFrame({'a': np.random.choice(['x', 'y'], size=50),
'b': np.random.rand(50)},
index=pd.date_range('2010', periods=50))
>>> df.head()
a b
2010-01-01 y 0.959568
2010-01-02 x 0.784837
2010-01-03 y 0.745148
2010-01-04 x 0.965686
2010-01-05 y 0.654552
你可以这样做:
>>> # `a` is dropped because it is non-numeric
>>> df.groupby(pd.Grouper(freq='M')).sum()
b
2010-01-31 18.5123
2010-02-28 7.7670
但以上内容有点不必要,因为您只是在索引上进行分组。相反,您可以这样做:
>>> df.resample('M').sum()
b
2010-01-31 16.168086
2010-02-28 9.433712
产生相同的结果。
相反,Grouper() 会很有用:
>>> df.groupby([pd.Grouper(freq='M'), 'a']).sum()
b
a
2010-01-31 x 8.9452
y 9.5671
2010-02-28 x 4.2522
y 3.5148
有关更多详细信息,请查看 Ted Petrou 的Pandas Cookbook 的第 7 章。
【讨论】:
df.groupby([pd.Grouper(freq='M'), 'brad']).mean()之类的事情吗?
pandas.TimeGrouper() was deprecated 在 pandas v0.21 中支持 pandas.Grouper()。
请改用pandas.Grouper()。
【讨论】: