Home > Mobile >  Mapping values with a condition, Pandas
Mapping values with a condition, Pandas

Time:10-28

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:

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

CodePudding user response:

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
  • Related