首页 > 解决方案 > 如何在 Pandas 中执行 groupby 并计算原始数据集中每一行的平均值

问题描述

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

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

我想将上述数据集转换为以下我想Mean在行分组时显示 Cost 列和['Brand', 'Model']一个Result列,该列是列值的总和:MeanTax

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函数,但没有得到如上所需结果的方法。

期待您的回复。谢谢你。

标签: pythonpandasdataframepandas-groupby

解决方案


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

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

推荐阅读