python - 如何根据其他列的类别更改具有不同百分比值的列的值
问题描述
假设我有一个数据框:
df
cat income
1 10
2 20
2 50
3 60
1 20
我想根据计划明智地应用固定百分比增加类别:
If the cat==1-----> income * 1.1 (10% increase)
If the cat==2-----> income * 1.2 (20% increase)
If the cat==3-----> income * 1.3 (30% increase)
然后我需要将增加的列附加到上述数据框中,如下所示:
df
cat income increased_income
1 10 11
2 20 24
2 50 60
3 60 78
1 20 22
我怎样才能使用熊猫实现上述目标?
解决方案
尝试:
cat_map={1:1.1, 2:1.2, 3:1.3}
df["increased_income"]=df["income"].mul(df["cat"].map(cat_map))
输出:
cat income increased_income
0 1 10 11.0
1 2 20 24.0
2 2 50 60.0
3 3 60 78.0
4 1 20 22.0
推荐阅读
- python - 为在 Gunicorn 上运行的 Flask-SQLAlchemy 应用程序选择 DB pool_size
- sql - 如何使用带有 MONEY 数据类型的 WHERE 子句?
- javascript - 包含的页面 javascript 范围
- python - Python 正则表达式忽略空行
- javascript - 单击时自动重新加载延迟
- r - 关于tidygraph中复制失败的问题
- .net - 如何使用默认基地址配置 WCF 服务?
- reactjs - 如何在 React 应用程序中提交时将一个对象从一个数组移动到另一个数组
- android - 使用 Android Studio 将 SQLite 中的数据显示为动态卡片
- html - mouseover/mouseout Angular 上的最佳方式样式