Python Pandas:分组中的分组和平均?

问题描述 投票:87回答:2

我有一个这样的数据框架。

cluster  org      time
   1      a       8
   1      a       6
   2      h       34
   1      c       23
   2      d       74
   3      w       6 

我想计算每个org每个cluster的平均时间。

预期的结果。

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

我不知道如何在Pandas中进行计算,有谁能帮助我吗?

python pandas group-by mean
2个回答
123
投票

如果你想先把平均数的组合上的 ['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

12
投票

我只需这样做,这就是你想要的逻辑。

df.groupby(['org']).mean().groupby(['cluster']).mean()
© www.soinside.com 2019 - 2024. All rights reserved.