Python Pandas:分组和平均? [英] Python Pandas : group by in group by and average?

查看:35
本文介绍了Python Pandas:分组和平均?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

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.

预期结果:

cluster mean(time)
1       15 ((8+6)/2+23)/2
2       54   (74+34)/2
3       6

我不知道如何在 Pandas 中做到这一点,有人可以帮忙吗?

I do not know how to do it in Pandas, can anybody help?

推荐答案

如果你想先对 ['cluster', 'org'] 的组合取均值,然后在 cluster 组,可以使用:

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

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 组的平均值,那么你可以使用:

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

你也可以在 ['cluster', 'org'] 上使用 groupby 然后使用 mean():

You can also use groupby on ['cluster', 'org'] and then use 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:分组和平均?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆