Nishant
Nishant

Reputation: 1121

How to change value of column with different percentage values depending on the categories of other column

Say I have a data frame as:

df

cat   income 
1     10
2     20
2     50
3     60
1     20

I want to apply a fixed percentage increase category wise as per the scheme:

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)

Then i need to append the increased column to the above data frame as below:

df

cat   income increased_income
1     10      11
2     20      24
2     50      60
3     60      78
1     20      22

How can i achieve the above using pandas?

Upvotes: 1

Views: 347

Answers (3)

wwnde
wwnde

Reputation: 26676

Condition using boolean select

a=df['cat']==1
b=df['cat']==2
c=df['cat']==3

Apply np.where

df['increased_income']=np.where(a,(df['income']*1.1),(np.where(b,(df['income']*1.2),(np.where(c,(df['income']*1.3),df['income'])))))
df

Outcome

enter image description here

Upvotes: 0

Erfan
Erfan

Reputation: 42916

First we create factors of your cat by dividing it by 10 and adding 1. Then we multiple these factors with your income

df['increased_income'] = df['income'].mul(df['cat'].div(10).add(1))
# or with basic Python operators
# df['increased_income'] = df['income'] * (df['cat'] / 10 + 1)

   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

Upvotes: 1

Georgina Skibinski
Georgina Skibinski

Reputation: 13397

Try:

cat_map={1:1.1, 2:1.2, 3:1.3}

df["increased_income"]=df["income"].mul(df["cat"].map(cat_map))

Outputs:

   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

Upvotes: 3

Related Questions