Replace the value of dictionary with the value of another dictionary

Viewed 60

1.I have a dataframe Input:

emp data
pp  ab
qq  bc
rr  cs
ss  dp

I convert it into dictionary:

df_r.to_dict('dict')

2.I have another dataframe:

ID name
1  s
2  ab
3  dp
4  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  s
2  pp
3  ss
4  t

Code: I tried

df= [df_r.get(x, x) for x in df['Value'].values]
df

issue: not doing any replacing of values.

1 Answers

Try:

df2["name"] = df2["name"].map(df1.set_index("data")["emp"]).fillna(df2["name"])
print(df2)

Prints:

   ID name
0   1    s
1   2   pp
2   3   ss
3   4    t
Related