Python 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

解决方法

我有一个这样的数据框:

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

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