【问题标题】:How to perform groupby in Pandas and compute mean of each row in original dataset如何在 Pandas 中执行 groupby 并计算原始数据集中每一行的平均值
【发布时间】:2019-02-08 19:13:47
【问题描述】:

我有一个电子表格,其中包含以下格式的数据:

Brand | Model    | Year | Cost  | Tax
--------------------------------------
Apple | iPhone 7 | 2017 | $1000 | $100

Apple | iphone 7 | 2018 | $800  |  $80

Xiomi | Note 5   | 2017 | $300  |  $30

Xiomi | Note 5   | 2018 | $200  |  $20

我想将上述数据集转换为以下内容,当行按['Brand', 'Model']Result 列分组时,我想显示 Cost 列的 Mean 和 @ 的总和987654325@ 和Tax 列值:

Brand | Model    | Year | Cost  | Mean   | Tax    |  Result
------------------------------------------------------------ 
Apple | iPhone 7 | 2017 | $1000 | $900   | $100   |  $1000

Apple | iphone 7 | 2018 | $800  | $900   | $80    |  $980

Xiomi | Note 5   | 2017 | $300  | $250   | $30    |  $280

Xiomi | Note 5   | 2018 | $200  | $250   | $25    |  $275

我一直在尝试使用 groupby 函数,但没有得到如上所示结果的方法。

期待您的回复。谢谢。

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    首先使用replace 将值转换为整数,通过transform 获取mean,然后sum,最后在必要时转换回字符串:

    cols = ['Cost','Tax']
    df[cols] = df[cols].replace('\$','', regex=True).astype(int)
    df['Mean'] = df.groupby(['Brand', 'Model'])['Cost'].transform('mean')
    
    df['Result'] = df[['Mean','Tax']].sum(axis=1)
    print (df)
       Brand     Model  Year  Cost  Tax  Mean  Result
    0  Apple  iPhone 7  2017  1000  100  1000    1100
    1  Apple  iphone 7  2018   800   80   800     880
    2  Xiomi    Note 5  2017   300   30   250     280
    3  Xiomi    Note 5  2018   200   20   250     270
    

    然后:

    cols1 = cols + ['Result', 'Mean']
    df[cols1] = '$' + df[cols1].astype(str)
    print (df)
       Brand     Model  Year   Cost   Tax   Mean Result
    0  Apple  iPhone 7  2017  $1000  $100  $1000  $1100
    1  Apple  iphone 7  2018   $800   $80   $800   $880
    2  Xiomi    Note 5  2017   $300   $30   $250   $280
    3  Xiomi    Note 5  2018   $200   $20   $250   $270
    

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 2020-04-10
      相关资源
      最近更新 更多