【问题标题】:How to group by day and month in pandas?如何在熊猫中按天和月分组?
【发布时间】:2019-10-25 00:54:38
【问题描述】:

给定一个这样的系列

    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 日等组合在一起?

我实际上是在尝试找到几年中一年中每一天的最大值,所以它不必是 groupby。如果有更简单的方法来做到这一点,那就太好了。

【问题讨论】:

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


    【解决方案1】:

    您可以将索引转换为日期时间,然后使用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()
    

    【讨论】:

    • 谢谢。为什么我得到NameError: name 'series' is not define 的线路:series.groupby(dailymax.to_datetime(series.index).strftime('%b-%d')).max()
    • @Dirk 系列是指您的系列。如果你想要df.groupby(pd.to_datetime(df.index).strftime('%b-%d'))['Date_Value'].max()。重点是接受这个答案并将其塑造成适合您的数据和变量命名方案。
    【解决方案2】:

    作为替代方案,您可以使用数据透视表:

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

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

    【讨论】:

      【解决方案3】:

      为什么不保持简单!

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-17
        • 2016-06-24
        • 1970-01-01
        • 2014-12-15
        • 1970-01-01
        • 2020-03-24
        • 2019-11-17
        • 2019-10-10
        相关资源
        最近更新 更多