1

Let's take these sample dataframes :

df = pd.DataFrame({'Id':['1','2','3','4','5'], 'Value':[9,8,7,6,5]})

  Id  Value
0  1      9
1  2      8
2  3      7
3  4      6
4  5      5

df_name = pd.DataFrame({'Id':['1','2','4'], 'Name':['Andrew','Jason','John']})

  Id    Name
0  1  Andrew
1  2   Jason
2  4    John

I would like to add in the Id column of df the Name of the person (obtainable in df_name) if it exists, in brackets. I know how to do this with a for loop over the Id column of df but it is inefficient with large dataframes. Do you know please a better way do to this ?

Expected output :

           Id  Value
0  1 (Andrew)      9
1   2 (Jason)      8
2           3      7
3    4 (John)      6
4           5      5

1 Answer 1

1

Use Series.map for match values, add () and replace non matche values by original column in Series.fillna:

df['Id'] = ((df['Id'] + ' (' + df['Id'].map(df_name.set_index('Id')['Name']) + ')')
               .fillna(df['Id']))
print (df)
           Id  Value
0  1 (Andrew)      9
1   2 (Jason)      8
2           3      7
3    4 (John)      6
4           5      5
Sign up to request clarification or add additional context in comments.

Comments

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.