我有数据 df:
month name duration
5 abc 09:03:00
5 abc 09:09:00
5 eef 10:03:00
5 eef 09:03:00
5 eef 09:03:00
5 ttk 10:03:00
5 abc 09:03:00
5 ttk 09:23:00
6 ttk 09:03:00
6 abc 11:03:00
我需要对此进行分组才能得到如下结果:
month name name_size name_nuique duration_mean
5 abc 3 1 09:05:00
eef 3 1 09:23:00
ttk 2 1 09:43:00
6 abc 1 1 09:03:00
ttx 1 1 11:03:00
请让我知道如何执行此操作。 我尝试做
df.groupby(['month','name'], sort=False).agg({'name':['size','nunique'],
'duration':['mean']})
但我收到错误消息:
No numeric types to aggregate
最佳答案
标准 pandas mean()
无法处理时间增量。将列转换为时间增量后,对其应用自定义 lambda 函数:
df["duration"] = pd.to_timedelta(df["duration"])
df.groupby(["month", "name"], sort=False).agg({
"name": ["size", "nunique"],
"duration": [lambda x: x.mean()]})
关于python - 按平均小时数分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52697002/