Home > Back-end >  Subtract value of column based on another column
Subtract value of column based on another column

Time:02-22

I have a big dataframe (the following is an example)

country value
portugal 86
germany 20
belgium 21
Uk 81
portugal 77
UK 87

I want to subtract values by 60 whenever the country is portugal or UK, the dataframe should look like (Python)

country value
portugal 26
germany 20
belgium 21
Uk 21
portugal 17
UK 27

CodePudding user response:

IUUC, use isin on the lowercase country string to check if the values is in a reference list, then slice the dataframe with loc for in place modification:

df.loc[df['country'].str.lower().isin(['portugal', 'uk']), 'value'] -= 60

output:

    country  value
0  portugal     26
1   germany     20
2   belgium     21
3        Uk     21
4  portugal     17
5        UK     27

CodePudding user response:

Use numpy.where:

In [1621]: import numpy as np

In [1622]: df['value'] = np.where(df['country'].str.lower().isin(['portugal', 'uk']), df['value'] - 60, df['value'])

In [1623]: df
Out[1623]: 
    country  value
0  portugal     26
1   germany     20
2   belgium     21
3        Uk     21
4  portugal     17
5        UK     27
  • Related