pandas 石斑鱼 vs 时间石斑鱼
pandas grouper vs time grouper
新的pandas版本弃用了TimeGrouper
,所以我们应该使用常规的Grouper
。
旧代码:
df['column_name'].groupby(pd.TimeGrouper("M")).mean().plot()
在旧版本 pandas 中工作正常。但是,none 个:
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()
正如我在评论中所说,key应该是石斑鱼中的datetime。默认情况下,Timegrouper 会将其转换为日期时间,因此请使用
df['column_name'] = pd.to_datetime(df['column_name'])
# new version
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()
新的pandas版本弃用了TimeGrouper
,所以我们应该使用常规的Grouper
。
旧代码:
df['column_name'].groupby(pd.TimeGrouper("M")).mean().plot()
在旧版本 pandas 中工作正常。但是,none 个:
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()
正如我在评论中所说,key应该是石斑鱼中的datetime。默认情况下,Timegrouper 会将其转换为日期时间,因此请使用
df['column_name'] = pd.to_datetime(df['column_name'])
# new version
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()