【问题标题】:Python: average value for timedelta after dataframe groupingPython:数据帧分组后timedelta的平均值
【发布时间】:2021-02-02 03:58:33
【问题描述】:

我知道,这是一个非常受欢迎的问题,并且有很多关于平均 fo timedelta 和 datetime 参数的话题。不幸的是,我坚持自己的方法,并想就以下任务寻求您的帮助:

作为行的结果:

time_to_rent = user_payments[user_payments.rentComplete].groupby(['rentId','creditCardId','rentComplete'], as_index=False).agg({'createdAt': np.min, 'updatedAt': np.max})

我得到了数据框(dict 格式):

time_to_rent = {'rentId': {0: 43.0, 1: 87.0, 2: 140.0, 3: 454.0, 4: 1458.0}, 'creditCardId': {0: 40, 1: 40, 2: 40, 3: 40, 4: 40}, 'rentComplete': {0: True, 1: True, 2: True, 3: True, 4: False}, 'createdAt': {0: Timestamp('2020-08-24 16:13:11.850216'), 1: Timestamp('2020-09-10 10:47:31.748628'), 2: Timestamp('2020-09-13 15:29:06.077622'), 3: Timestamp('2020-09-24 08:08:39.852348'), 4: Timestamp('2020-10-19 08:54:09.891518')}, 'updatedAt': {0: Timestamp('2020-08-24 20:26:31.805939'), 1: Timestamp('2020-09-10 20:05:18.759421'), 2: Timestamp('2020-09-13 18:38:10.044112'), 3: Timestamp('2020-09-24 08:53:22.512533'), 4: Timestamp('2020-10-19 09:24:03.982986')}, 'rent_time': {0: Timedelta('0 days 04:13:19.955723'), 1: Timedelta('0 days 09:17:47.010793'), 2: Timedelta('0 days 03:09:03.966490'), 3: Timedelta('0 days 00:44:42.660185'), 4: Timedelta('0 days 00:29:54.091468')}}

然后我再添加一列:

time_to_rent['rent_time'] = time_to_rent['updatedAt'] - time_to_rent['createdAt']

我想按“creditCardId”对 time_to_rent 进行分组,并为“rent_time”列取平均值。

该代码返回错误:

average_per_user = time_to_rent.groupby('creditCardId').agg({'rent_time' : np.mean})

这是错误返回:

~\anaconda3\lib\site-packages\pandas\core\groupby\groupby.py in _cython_agg_general(self, how, alt, numeric_only, min_count)
    906 
    907         if len(output) == 0:
--> 908             raise DataError("No numeric types to aggregate")
    909 
    910         return self._wrap_aggregated_output(output)

DataError: No numeric types to aggregate

不知道为什么 len(output) 等于 0 ...

【问题讨论】:

  • 这里有什么错误?
  • 行尾缺少“)”。
  • 是的,我打错了。

标签: python pandas average aggregation timedelta


【解决方案1】:

如果我理解正确,您需要从df.rentComplete 中排除False 值(并使用) 关闭整个事物)。在 Pandas 中使用布尔列进行过滤很简单:

average_per_user = time_to_rent[time_to_rent.rentComplete] \
    .groupby('creditCardId').agg({'rent_time' : np.mean})

【讨论】:

  • 谢谢!看起来我的问题不在 agg 参数中,而是在“creditCardId”列中的奇怪值中:这是错误:DataError: No numeric types to aggregate
【解决方案2】:

试试这个:

average_per_user = time_to_rent.groupby('creditCardId').mean()['rent_time']

【讨论】:

  • 谢谢,但不起作用:DataError:没有要聚合的数字类型。奇怪...我只留下了 average_per_user = time_to_rent.groupby('creditCardId') 并返回: 当我打印 average_per_user
  • 试试:average_per_user = time_to_rent.groupby('creditCardId').mean()
  • 也请附上输出
  • 我更新了上面的问题。看起来问题不在 .mean() 中。数据框中没有参数“creditCardId”。
  • 能否请您将dict格式的df转发给我,让我附上完整的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 2021-11-02
  • 2019-01-07
  • 2016-11-08
  • 2023-02-21
  • 2015-07-26
相关资源
最近更新 更多