【问题标题】:python, pandas, calculate several means with groupby [closed]python,pandas,用groupby计算几种方法[关闭]
【发布时间】:2014-09-01 00:50:02
【问题描述】:

我的问题:我有以下数组,我想确定每个单词的 count1、count2 和 count3 的平均值。我想我必须使用“groupby”方法,但我不明白它是如何计算多个平均值的。

     word  count1 count2 count3
0    a        30      10      8
1    the      20      12      0
2    a        60      15     14
3    an       5       13      8
4    the      10      4       5

非常感谢您的帮助

【问题讨论】:

  • 与其同时提出两个问题,不如提出两个不同的问题。
  • 第一个问题的答案阅读missing data,第二个问题探索groupby
  • 谢谢你的建议,我做到了。但我仍然无法理解 groupby 文档 :(

标签: python pandas mean


【解决方案1】:

在这种情况下,您可以使用 `df.groupby('word').mean()`。 groupby 方法告诉 Pandas 通过查看“单词”列来对数据进行分组。然后我们通过取平均值来聚合数据。 (还有很多其他选项可用,例如 sum、min、max。)

word count1 count2 count3 a 45 12.5 11.0 an 5 13.0 8.0 the 15 8.0 2.5

要更全面地理解它,请尝试在一个简单的示例数据框上运行 groupby 以查看您可以用它做什么,并阅读上面 cmets 中链接上的文档。

【讨论】:

  • 但我不明白如何用 Serie df.groupby('word').mean() 形成您显示的数组。有没有一种自然的方法可以将其重建为形状良好的 DataFrame?
  • 保存df2 = df.groupby('word').mean()然后重置索引df2 = df2.reset_index
  • 你太棒了!谢谢 !! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 2021-07-25
  • 2019-02-02
  • 2017-01-26
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多