Home > Software design >  Add value to column based on another column
Add value to column based on another column

Time:04-07

I have a dateframe as shown below

ID value country
1 20 DE
21 10 IND

I want to add 4 to the 'value' column when country = DE such that the dataframe becomes

ID value country
1 24 DE
21 10 IND

I tried the following code but Its not working and I am getting an error

def add_buffer(df):
    if df.country == 'DE':
        df.value = df.value 4
    else:
        df.value = df.value
    return df
df1 = add_buffer(df)

CodePudding user response:

You can use .loc to update value only where country is equal to DE

import pandas as pd
df = pd.DataFrame({'ID': {0: 1, 1: 21}, 'value': {0: 20, 1: 10}, 'country': {0: 'DE', 1: 'IND'}})
df.loc[df['country'].eq('DE'),'value'] =4

print(df)

Output

   ID  value country
0   1     24      DE
1  21     10     IND
  • Related