2

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)

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Just a quick note that map and replace behave differently on not-found items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.