Python pandas groupby聚合时mean()处理rent_time列报错问题
报错原因
- 当前使用的pandas 1.x版本中,
groupby聚合默认仅识别原生数值类型列,会自动过滤Timedelta这类非原生数值的类型。 - 单独执行
time_to_rent['rent_time'].mean()时,是直接对单条Timedelta类型的Series调用均值方法,不经过groupby的类型过滤逻辑,因此运行正常。 - 执行分组聚合时,groupby默认找不到可统计的数值列,直接抛出
No numeric types to aggregate错误。 - 赋值后返回
DataFrameGroupBy对象是pandas的正常惰性机制:groupby()本身仅生成分组对象,只有执行完mean()、agg()这类聚合操作后,才会生成最终的统计结果DataFrame。
修复代码
方法1:显式关闭类型过滤
给聚合方法传入numeric_only=False参数,强制允许计算Timedelta类型:
time_to_rent.groupby('creditCardId', as_index=False)[['rent_time']].mean(numeric_only=False)
方法2:自定义聚合逻辑
直接对分组后的时间序列取均值,绕开默认类型过滤规则:
time_to_rent.groupby('creditCardId', as_index=False)['rent_time'].agg(lambda x: x.mean())
若需要匹配示例中的列名rent_time mean,可追加列重命名操作:
# 以方法1为例 time_to_rent.groupby('creditCardId', as_index=False)[['rent_time']].mean(numeric_only=False)\ .rename(columns={'rent_time': 'rent_time mean'})
执行后即可得到预期结果:
| creditCardId | rent_time mean |
|---|---|
| 40 | 0 days 05:08:10.562342 |
内容的提问来源于stack exchange,提问作者OcMaRUS
相关产品推荐
相关产品推荐

