【问题标题】:Issue with Groupby function in PandasPandas 中 Groupby 函数的问题
【发布时间】:2021-03-31 13:03:04
【问题描述】:

我正在尝试获取具有时间戳和各种其他字段的数据帧,并按四舍五入的时间戳(到最接近的分钟)分组,并取另一个字段的平均值。我收到错误 no numeric value to aggregate

我正在像这样对时间戳列进行四舍五入:

df['time'] = df['time'].dt.round('1min')

聚合列的形式为:0 days 00:00:00.054000

df3 = (
    df
    .groupby([df['time']])['total_diff'].mean()
    .unstack(fill_value=0)
    .reset_index()
)

我意识到 total_diff 列是一个时间增量字段,但我原以为这仍会被视为数字?

我的理想输出应包含以下列:四舍五入的时间戳、分组在该时间戳中的记录数、按四舍五入的时间戳计算的平均 total_diff。我怎样才能做到这一点?

编辑 示例行:

[index, id, time, total_diff]
[400, 5fdfe9242c2fb0da04928d55, 2020-12-21 00:16:00, 0 days 00:00:00.055000]
[401, 5fdfe9242c2fb0da04928d56, 2020-12-21 00:16:00, 0 days 00:00:00.01000]
[402, 5fdfe9242c2fb0da04928d57, 2020-12-21 00:15:00, 0 days 00:00:00.05000]

时间列不是唯一的。我想按时间列分组,计算分组到每个时间桶的行数,并为每个时间桶生成 total_diff 的平均值。

期望的结果:

[time, count, avg_total_diff]
[2020-12-21 00:16:00, 2, .0325]

【问题讨论】:

  • 请与预期输出共享示例输入。

标签: python pandas aggregation


【解决方案1】:

默认情况下DataFrame.groupby.mean 具有numeric_only=True,而数字 考虑intboolfloat。要同时使用timedelta64[ns],您必须将其设置为False .

样本数据

import pandas as pd

df = pd.DataFrame(pd.date_range('2010-01-01', freq='2T', periods=6))
df[1] = df[0].diff().bfill()
#                    0               1
#0 2010-01-01 00:00:00 0 days 00:02:00
#1 2010-01-01 00:02:00 0 days 00:02:00
#2 2010-01-01 00:04:00 0 days 00:02:00
#3 2010-01-01 00:06:00 0 days 00:02:00
#4 2010-01-01 00:08:00 0 days 00:02:00
#5 2010-01-01 00:10:00 0 days 00:02:00

df.dtypes
#0     datetime64[ns]
#1    timedelta64[ns]
#dtype: object

代码

df.groupby(df[0].round('5T'))[1].mean()
#DataError: No numeric types to aggregate

df.groupby(df[0].round('5T'))[1].mean(numeric_only=False)
#0
#2010-01-01 00:00:00   0 days 00:02:00
#2010-01-01 00:05:00   0 days 00:02:00
#2010-01-01 00:10:00   0 days 00:02:00
#Name: 1, dtype: timedelta64[ns]

【讨论】:

  • 我认为 resample 可能比舍入 + groupby 更直接
  • @ALollz 如何包含每组的行数?那么答案将是完美的。
  • @PaulH 是的,可能只是在复制 OP 所做的一切。 resample 不能解决问题,因为它基本上等同于 groupby,而问题在于 GroupBy.mean,它不会改变。
  • @StormsEdge,也是一种获取计数的可能方法:df.groupby('time').agg(Mean=('total_diff', lambda x: x.mean(numeric_only=False)), Count=('total_diff', 'count'))
  • @CainãMaxCouto-Silva 谢谢!
猜你喜欢
  • 2020-07-28
  • 2018-11-05
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
  • 2015-05-14
  • 2017-08-04
相关资源
最近更新 更多