我有一个这样的数据框:
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
您也可以使用
groupby
在 ['cluster', 'org']
然后使用 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 Pandas : group by in group by and average?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748876/