python - group by 分组和平均

标签 python pandas group-by mean

我有一个这样的数据框:

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

你也可以在['cluster', 'org']上使用groupby,然后使用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 - group by 分组和平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328646/

相关文章:

python - 将相关矩阵转换为 pandas 中的 3 列数据框?

python - Pandas 数据框 : Group by two columns and then average over another column

sql - MySQL - 使用 UNION ALL 和 GROUP BY 进行搜索

python - Pandas Apply 函数引用列名

python - 持续计算 pandas 数据框中大于阈值的值数量

python - Python 3 中小数到 2 位的钱

python - 带有基于另一列的标记的 Pandas 线图

ruby-on-rails-3 - Rails 3 : . group() 由 created_at 排序

python - 如何创建仅包含唯一值的随机列表?

python - aiohttp:设置每秒最大请求数