【问题标题】:How do I calculate the mean of one column according to a value in a second column?如何根据第二列中的值计算一列的平均值?
【发布时间】:2019-07-04 08:49:28
【问题描述】:

我在 DataFrame 中有 2 列,我正在寻找 Python 中的以下解决方案。

我的数据框目前看起来像这样:

columns: INDUSTRY         Revenue
         Service          100
         Manufacturing    50
         Service          200
         Manufacturing    100
         Public           60

我想要的是 DataFrame 中每个 INDUSTRY 类型的平均值:

columns: INDUSTRY         Revenue
         Service          150
         Manufacturing    75
         Public           60

我知道如何在 R 中使用函数表执行此操作,但我只是从 python 开始。谢谢

【问题讨论】:

  • 您的代码是必需的
  • 使用.groupby()

标签: python dataframe average


【解决方案1】:

在 python 中它称为 groupby,因为您的数据框称为 Industry,您必须使用:

Industry.groupby('Industry')['Revenue'].mean()

在 stackoverflow 上有几个例子:Pandas group-by and sum

【讨论】:

  • 谢谢,它工作。如果我想将 groupby 转换为 DataFrame:pd.DataFrame(Industry),会发生什么情况是第一行的列不在同一级别。列名称 Industry 从第 2 行开始。我该如何解决?
  • 我不确定你到底是什么意思,但把它放回数据框中:df2 = Industry.gorupby('Industry')['Revenue'].mean().reset_index()should help you
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
相关资源
最近更新 更多