pandas 大熊猫石斑鱼与时间石斑鱼

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47015886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:43:04  来源:igfitidea点击:

pandas grouper vs time grouper

pythonpandasgroupingdatetimeindex

提问by Georg Heiler

The new pandas version deprecates the TimeGrouper, so we should use the regular Grouper.

新的 Pandas 版本弃用了TimeGrouper,所以我们应该使用常规的Grouper.

The old code:

旧代码:

df['column_name'].groupby(pd.TimeGrouper("M")).mean().plot()

works fine in the old version of pandas. However, none of:

在旧版本的Pandas中工作正常。但是,没有一个:

df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()
df['column_name'].groupby(pd.Grouper(freq="M")).mean().plot()

works in the new version. Eiter the key is considered to be missing, or pandas complains about:

在新版本中工作。Eiter key 被认为丢失,或者 pandas 抱怨:

Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Float64Index'

edit

编辑

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()

回答by Bharath

As I said in the comment key should be datetime in grouper. Timegrouper by default converts it to datetime so use

正如我在评论中所说的,应该是 grouper 中的 datetime。默认情况下,Timegrouper 将其转换为日期时间,因此请使用

df['column_name'] = pd.to_datetime(df['column_name'])
# new version
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()