简体   繁体   English

如何使用 pd.Grouper 按月对日期进行分组?

[英]How do I group date by month using pd.Grouper?

I've searched stackoverflow to find out how to group DateTime by month and for some reason I keep receiving this error, even after I pass the dataframe through pd.to.datetime我已经搜索了 stackoverflow 以了解如何按月对 DateTime 进行分组,并且由于某种原因,即使在我通过pd.to.datetime传递数据帧之后,我仍然收到此错误

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'类型错误:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但有一个“Int64Index”实例

df['Date'] = pd.to_datetime(df['Date'])
df['Date'].groupby(pd.Grouper(freq='M'))

When I pull the datatype for df['Date'] it shows dtype: datetime64[ns] Any, ideas why I keep getting this error?当我为df['Date']提取数据类型时,它显示dtype: datetime64[ns] Any,为什么我不断收到此错误的想法?

The reason is simple: you didn't pass a groupby key to groupby .原因很简单:您没有将 groupby 键传递给groupby

What you want is to group the entire dataframe by the month values of the contents of df['Date'] .您想要的是按df['Date']内容的月份值对整个数据框进行分组。

However, what df['Date'].groupby(pd.Grouper(freq='M')) actually does is first extract a pd.Series from the DataFrame's Date column.然而, df['Date'].groupby(pd.Grouper(freq='M'))实际上首先从 DataFrame 的Date列中提取一个pd.Series Then, it attempts to perform a groupby on that Series ;然后,它尝试对该Series执行 groupby ; without a specified key, it defaults to attempting to group by the index, which is of course numeric.没有指定的键,它默认尝试按索引分组,这当然是数字。

This will work:这将起作用:

df.groupby(pd.Grouper(key='Date', freq='M'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM