【问题标题】:Get mean per column per partition in Pandas [duplicate]在 Pandas 中获取每个分区的每列平均值 [重复]
【发布时间】:2018-11-20 21:28:19
【问题描述】:

我正在尝试获取 DataFrame 的每个分区的每个列的平均值,例如这个:

  country      city  sales  stock
0      UK    London      1     34
1      UK     Leeds      2     20
2      UK     Leeds      3     21
3      RO      Cluj      4     24
4      RO      Cluj      5     25
5      RO Bucharest      6     25

也就是说,我想得到salesstock 的平均值,并将它们聚合成countrycity 的独特组合。因此,生成的 DataFrame 应该是:

  country      city  sales  stock
0      UK    London      1     34
1      UK     Leeds    2.5   20.5
2      RO      Cluj    4.5   24.5
3      RO Bucharest      6     25

我的国家 - 城市分区的重复行已聚合为一行,具有平均值。

我研究了有关pandas.DataFrame.mean() 的文档和诸如this one 之类的SO 问题和答案,但没有一个能以直截了当的方式帮助我。任何帮助表示赞赏。

【问题讨论】:

标签: python pandas mean partition


【解决方案1】:

groupby

df.groupby(['country', 'city']).mean()

                   sales  stock
country city                   
RO      Bucharest    6.0   25.0
        Cluj         4.5   24.5
UK      Leeds        2.5   20.5
        London       1.0   34.0

设置索引

df.set_index(['country', 'city']).mean(level=[0, 1])

不设置索引

df.groupby(['country', 'city'], as_index=False, sort=False).mean()


  country       city  sales  stock
0      UK     London    1.0   34.0
1      UK      Leeds    2.5   20.5
2      RO       Cluj    4.5   24.5
3      RO  Bucharest    6.0   25.0

【讨论】:

  • 准确地说,df.groupby(['country', 'city'], as_index=False, sort=False).mean()
猜你喜欢
  • 1970-01-01
  • 2020-03-09
  • 2022-11-10
  • 2019-11-23
  • 1970-01-01
  • 2021-08-07
  • 2020-01-17
  • 2021-01-30
  • 1970-01-01
相关资源
最近更新 更多