新的 pandas 版本弃用了
TimeGrouper
,所以我们应该使用常规的 Grouper
。
旧代码:
df['column_name'].groupby(pd.TimeGrouper("M")).mean().plot()
在旧版本的 pandas 中运行良好。然而,没有一个:
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()
df['column_name'].groupby(pd.Grouper(freq="M")).mean().plot()
适用于新版本。 要么认为钥匙丢失,要么 pandas 抱怨:
Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Float64Index'
import pandas as pd
df = pd.DataFrame({'column_name':['2017-01-01', '2017-01-02'],
'column_value':[1,3]})
df
df.index = pd.DatetimeIndex(df.column_name)
df.index
# old version
df['column_value'].groupby(pd.TimeGrouper("M")).mean().plot()
# new version
df.groupby(pd.Grouper(key='column_value', freq="M")).mean().plot()
正如我在评论中所说,键应该是石斑鱼中的日期时间。 Timegrouper 默认将其转换为日期时间,因此使用
df['column_name'] = pd.to_datetime(df['column_name'])
# new version
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()
既然您现在已将
df.index
设置为日期时间索引,那么您可以使用 resample
按月间隔进行聚合,如下所示:
df.resample('1ME').mean('column_value')
# returns the result as a Pandas.DataFrame
或者,这也有效:
df['column_value'].resample('1ME').mean()
# returns the result as a Pandas.Series