Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping values with a condition, Pandas

State         City
California    1
California    2
Lousiana      1
Virginia      2

dict = {1 : LA, 2 : SF}

I am trying to map the dictionary I have on the table with the condition that the "State" is California.

The expected result is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

State         City
California    LA
California    SF
Lousiana      1
Virginia      2

I have tried,

df['City'] = df['City'].where(df['State']=='California').map(dict)

but I get:

State         City
California    LA
California    SF
Lousiana      NaN
Virginia      NaN

>Solution :

Use boolean indexing:

dic = {1 : 'LA', 2 : 'SF'}

m = df['State'].eq('California')

df.loc[m, 'City'] = df.loc[m, 'City'].map(dic)

A fix of your approach (but less efficient than above) would be:

df['City'] = df['City'].mask(df['State']=='California', df['City'].map(dic))

output:

        State City
0  California   LA
1  California   SF
2    Lousiana    1
3    Virginia    2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading