简体   繁体   中英

Replace column values in python dataframe using dictionary based on condition

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM