首页 > 解决方案 > 如何根据其他列的类别更改具有不同百分比值的列的值

问题描述

假设我有一个数据框:

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

我怎样才能使用熊猫实现上述目标?

标签: pythonpandas

解决方案


尝试:

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

推荐阅读