python - 如何在 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列,该列是列值的总和:Mean
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函数,但没有得到如上所需结果的方法。
期待您的回复。谢谢你。
解决方案
首先使用 将值转换为整数,通过replace
获取,然后在必要时最后转换回字符串:mean
transform
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
推荐阅读
- ios - 在flutter中通过url使用.ipa文件时,启动发布的iOS应用程序未下载到多个设备
- kendo-ui - Kendo DropDownList 在选项中保留空格
- angular - 当我指定 sm 模态时,我仍然可以在后台看到 lg
- python - 为什么没有通过 Google Calendar API 将与会者添加到活动中?
- react-native - Expo:弹出到裸项目仅适用于 SDK 34 及更高版本
- python-3.x - 如何在 python/selenium 中为动态元素编写 xpath
- javascript - 将字符串传递给方法发送电子邮件
- python - 'function' 对象在新端点上没有属性 'get_extra_actions'
- sql - 错误:ntext 数据类型无法选择为 DISTINCT,因为它不可比较
- linux - 带有 Apache httpd.conf 文件的 Docker 卷权限