如何按日和月分组熊猫?

时间:2019-06-10 15:41:49

标签: python pandas datetime group-by pandas-groupby

给出这样的系列

    Date
2005-01-01    128
2005-01-02     72
2005-01-03     67
2005-01-04     61
2005-01-05     33
Name: Data_Value, dtype: int64

几年来,我如何将所有1月1日,所有1月2日等分组?

我实际上正在尝试查找几年中一年中每一天的最大值,因此不必进行分组。如果有更简单的方法可以做到这一点,那就太好了。

3 个答案:

答案 0 :(得分:2)

您可以将索引转换为日期时间,然后使用strftime获取日期格式的字符串进行分组:

df.groupby(pd.to_datetime(df.index).strftime('%b-%d'))['Date_Value'].max()

如果日期字符串中没有NaN,则也可以切片。这将返回格式为“ MM-DD”的字符串:

df.groupby(df.index.astype(str).str[5:])['Date_Value'].max()

答案 1 :(得分:1)

或者,您可以使用数据透视表:

重置索引和格式化​​日期列

df=df.reset_index()
df['date']=pd.to_datetime(df['index'])
df['year']=df['date'].dt.year
df['month']=df['date'].dt.month
df['day']=df['date'].dt.day

在“月和日”列上进行透视:

df_grouped=df.pivot_table(index=('month','day'),values='Date',aggfunc='max')

答案 2 :(得分:0)

为什么不只是保持简单!

max_temp = dfall.groupby([(dfall.Date.dt.month),(dfall.Date.dt.day)])['Data_Value'].max()
相关问题