Reputation: 157
1.I have a dataframe Input:
emp data
pp ab
qq bc
rr cs
ss dp
dictionary:
df_r.to_dict('dict')
2.I have another dataframe with name having string values:
ID name
1 ['u']['s']
2 ['v']['ab']
3 ['w']['dp']
4 ['x']['t']
dictionary :
df.to_dict('dict')
Expected result : I want to replace the value of name as per data's emp value
ID name
1 ['u']['s']
2 ['v']['pp']
3 ['w']['ss']
4 ['x']['t']
Code: I tried
mapper = dict(df_r[["data", "emp"]].values)
mapper
df.name = df.name.replace(mapper).values
df
issue: not doing any replacing of values. The dataframe remains unaffected.
Upvotes: 0
Views: 83
Reputation: 11
dict
then use it to update the second Dataframe. Steps:import pandas as pd
df1 = pd.DataFrame([['pp', 'ab'],
['qq','bc'],
['rr', 'cs'],
['ss', 'dp']],
columns=['emp', 'data'])
df2 = pd.DataFrame([['u', 's'],
['v', 'ab'],
['w', 'dp'],
['x', 't']],
columns=['ID', 'name'])
keys
, emp as values
:Make data as index in the Dataframe
then transforme into dict
df1_dict = df1.set_index('data').to_dict()['emp']
df2['name'] = df2['name'].replace(df1_dict)
output:
ID name
0 u s
1 v pp
2 w ss
3 x t
Upvotes: 1