我有一个像这样的数据框:
cluster org time
1 a 8
1 a 6
2 h 34
1 c 23
2 d 74
3 w 6
我想计算每个组织每个集群的平均时间。
预期结果:
cluster mean(time)
1 15 #=((8 + 6) / 2 + 23) / 2
2 54 #=(74 + 34) / 2
3 6
我不知道如何在 Pandas 中做到这一点,有人可以帮忙吗?
最佳答案
如果您想首先对 ['cluster', 'org']
组合取平均值,然后对 cluster
组取平均值,您可以使用:
In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
.groupby('cluster')['time'].mean())
Out[59]:
cluster
1 15
2 54
3 6
Name: time, dtype: int64
如果您只需要cluster
组的平均值,那么您可以使用:
In [58]: df.groupby(['cluster']).mean()
Out[58]:
time
cluster
1 12.333333
2 54.000000
3 6.000000
您还可以在 ['cluster', 'org']
上使用 groupby
,然后使用 mean()
:
In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
time
cluster org
1 a 438886
c 23
2 d 9874
h 34
3 w 6
关于python - 分组依据 分组依据 和 平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748876/