Python Pandas:分组和平均?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30328646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Pandas : group by in group by and average?
提问by UserYmY
I have a dataframe like this:
我有一个这样的数据框:
cluster org time
1 a 8
1 a 6
2 h 34
1 c 23
2 d 74
3 w 6
I would like to calculate the average of time per org per cluster.
我想计算每个集群每个组织的平均时间。
Expected result:
预期结果:
cluster mean(time)
1 15 ((8+6)/2+23)/2
2 54 (74+34)/2
3 6
I do not know how to do it in Pandas, can anybody help?
我不知道如何在 Pandas 中做到这一点,有人可以帮忙吗?
采纳答案by Zero
If you want to first take mean on the combination of ['cluster', 'org']
and then take mean on cluster
groups, you can use:
如果您想先对组合['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
If you want the mean of cluster
groups only, then you can use:
如果您只想要cluster
组的平均值,则可以使用:
In [58]: df.groupby(['cluster']).mean()
Out[58]:
time
cluster
1 12.333333
2 54.000000
3 6.000000
You can also use groupby
on ['cluster', 'org']
and then use mean()
:
您还可以使用groupby
on['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
回答by Vince Payandeh
I would simply do this, which literally follows what your desired logic was:
我会简单地这样做,它实际上遵循您想要的逻辑:
df.groupby(['org']).mean().groupby(['cluster']).mean()