【问题标题】:pandas dataframe groupby datetime month熊猫数据框分组日期时间月
【发布时间】:2023-03-20 11:50:01
【问题描述】:

考虑一个 csv 文件:

string,date,number
a string,2/5/11 9:16am,1.0
a string,3/5/11 10:44pm,2.0
a string,4/22/11 12:07pm,3.0
a string,4/22/11 12:10pm,4.0
a string,4/29/11 11:59am,1.0
a string,5/2/11 1:41pm,2.0
a string,5/2/11 2:02pm,3.0
a string,5/2/11 2:56pm,4.0
a string,5/2/11 3:00pm,5.0
a string,5/2/14 3:02pm,6.0
a string,5/2/14 3:18pm,7.0

我可以读进去,并将日期列重新格式化为日期时间格式:

b=pd.read_csv('b.dat')
b['date']=pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')

我一直在尝试按月对数据进行分组。似乎应该有一种明显的方式来访问月份并以此进行分组。但我似乎做不到。有人知道怎么做吗?

我目前正在尝试按日期重新索引:

b.index=b['date']

我可以像这样访问月份:

b.index.month

但是我似乎找不到按月汇总的功能。

【问题讨论】:

  • 如果您在应用任何答案时遇到困难,请记住,在这个问题(以及答案中)中,日期时间值被分配给数据框的索引。快速提示/提醒如下:如果您有一个 Datetime 列,您实际上可以通过执行 my_df.my_column.dt.month 访问单个 Yeay/Month/Day/Hour/Minute 值

标签: python pandas datetime pandas-groupby


【解决方案1】:

设法做到了:

b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])

或者

b.groupby(pd.Grouper(freq='M'))  # update for v0.21+

【讨论】:

  • 我认为更流行的方法是使用resample(当它提供您需要的功能时)或使用TimeGrouperdf.groupby(pd.TimeGrouper(freq='M'))
  • 获取结果DataFrame总和或平均值,df.groupby(pd.TimeGrouper(freq='M')).sum()df.groupby(pd.TimeGrouper(freq='M')).mean()
  • pd.TimeGrouper 已被弃用,取而代之的是 pd.Grouper,后者更灵活一些,但仍接受 freqlevel 参数。
  • 第一种方法似乎不起作用。它给出了错误,'Series object has no attribute 'month'' for a Series created via to_datetime.
  • @ely 答案隐含地依赖于原始问题中的行,其中b 在从 CSV 读取后被赋予索引。在b = pd.read_csv('b.dat') 行之后添加b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')。 [我刚才也编辑了答案。]
【解决方案2】:

(更新:2018 年)

请注意,pd.Timegrouper 已贬值并将被删除。改为使用:

 df.groupby(pd.Grouper(freq='M'))

【讨论】:

  • 查找 Grouper 文档 here 和频率规范 (freq=...) here。例如,freq=D 表示 freq=B 表示 工作日freq=W 表示 ,甚至freq=Q 表示 宿舍.
  • 我发现使用 'key' 来避免重新索引 df 很有用,如下所示:df.groupby(pd.Grouper(key='your_date_column', freq='M'))
  • 如果您按两列分组,这是否有效,其中只有一列是日期时间值列?
  • 加速那些想要按特定列(或更多)分组的人的进一步研究: df.groupby(['col1', pd.Grouper(key='date_col', freq='1M ')]).agg({ 'col2': 'sum', 'col3': 'max' })
【解决方案3】:

避免使用 MultiIndex 的一种解决方案是创建一个新的 datetime 列设置 day = 1。然后按此列分组。

正常化月份中的某天

df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
                   'Values': [5, 10, 15, 20]})

# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)

然后照常使用groupby

g = df.groupby('YearMonth')

res = g['Values'].sum()

# YearMonth
# 2017-09-01    20
# 2017-10-01    30
# Name: Values, dtype: int64

pd.Grouper比较

pd.Grouper 不同,此解决方案的微妙好处是,grouper 索引被标准化为每个月的开始,而不是结束,因此您可以通过get_group 轻松提取组:

some_group = g.get_group('2017-10-01')

计算 10 月的最后一天稍微麻烦一些。 pd.Grouper,从 v0.23 开始,支持 convention 参数,但这仅适用于 PeriodIndex grouper。

与字符串转换比较

上述想法的替代方法是转换为字符串,例如将日期时间2017-10-XX 转换为字符串'2017-10'。但是,不建议这样做,因为您失去了 datetime 系列(内部存储为连续内存块中的数字数据)与 object 系列字符串(存储为指针数组)相比的所有效率优势。

【讨论】:

  • 当已经有 day=1 值时,请参阅此答案以了解使用偏移量的正确方法:stackoverflow.com/a/45831333/9987623
  • @AlexK,pd.tseries.offsetspd.tseries.MonthBegin 有优势吗?
  • 抱歉,我的知识不足以区分它们。我刚刚添加了评论,因为您上面的 df['YearMonth'] = df['Date'] - pd.offsets.MonthBegin(1) 代码将已经是本月第一天的任何日期更改为上个月的第一天。
  • @AlexK,好地方,已相应更新答案。
【解决方案4】:

@jpp 的略微替代解决方案,但输出 YearMonth 字符串:

df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))

res = df.groupby('YearMonth')['Values'].sum()

【讨论】:

    【解决方案5】:

    要对时间序列数据进行分组,您可以使用方法resample。例如,按月分组:

    df.resample(rule='M', on='date')['Values'].sum()
    

    您可以找到带有偏移别名的列表here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 2017-08-22
      • 2017-02-05
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      相关资源
      最近更新 更多