Home > Software design >  Replace column values in python dataframe using dictionary based on condition
Replace column values in python dataframe using dictionary based on condition

Time:09-23

I have below dataframe

df = pd.DataFrame({'col1': {0: '4', 1: '4', 2: '2'},'col2': {0: 'USA', 1: 'England', 2: 'Japan'}})

>>> df
  col1     col2
0    4      USA
1    4  England
2    2    Japan

and I have below dictionary

dict_1 = {"USA" : 'Washington',"Japan" : 'Tokyo',"England" : 'London'}

I want to replace values in col2 using dict_1 but replace in rows where col1 == 2

Desired output is as below

  col1     col2
0    4      USA
1    4  England
2    2    Tokyo

I tried below method but it doesnt do anything

df.loc[df['col1'] == '2', 'col2'].replace(dict_1,inplace=True)

CodePudding user response:

Don't do inplace=True specially when you slice:

df.loc[df['col1']=='2', 'col2'] = df.loc[df['col1'] == '2', 'col2'].replace(dict_1)

Output:

  col1     col2
0    4      USA
1    4  England
2    2    Tokyo

CodePudding user response:

Another solution:

m = df.col1.eq("2")
df.loc[m, "col2"] = df.loc[m, "col2"].map(dict_1)

print(df)

Prints:

  col1     col2
0    4      USA
1    4  England
2    2    Tokyo
  • Related