Home > Software engineering >  PANDAS - using map and ignore case sensitivity
PANDAS - using map and ignore case sensitivity

Time:07-15

I have a data-frames:

df1 = pd.DataFrame({'Item': ["jetties","Jetty", "Joint use"], 'Team': ["Team_1", "Team_2", "Team_1"]})
df2 = pd.DataFrame({'Item': ["Jetty","Jetties","Joint use"]})

I am applying map to return Team values in df2:

df2['Team'] = df2['Item'].map(df1.set_index('Item')['Team'])

enter image description here

However, the result is giving me Nan for Jetties because of case sensitivity. Is there any way to ignore case sensitivity?

CodePudding user response:

You can convert your key to a defined case:

df2['Team'] = (df2['Item'].str.lower()
               .map(df1.assign(Item=df1['Item'].str.lower())
                       .set_index('Item')['Team'])
              )

output:

        Item    Team
0      Jetty  Team_2
1    Jetties  Team_1
2  Joint use  Team_1

CodePudding user response:

df = pd.merge(df1, df2, left_on=df1['Item'].str.lower(), right_on=df2['Item'].str.lower(), how='left').drop(['key_0', 'Item_x'], axis=1).rename(columns={'Item_y': 'Item'})
df = df[['Item', 'Team']]
df

I prefer joining data to using map most of the time

  • Related