Anubhav
Anubhav

Reputation: 157

Replacing the values inside the value of a dictionary

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

Answers (1)

Fadi
Fadi

Reputation: 11

Transform the first Dataframe to dict then use it to update the second Dataframe. Steps:

Dataframes:

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'])

Get dictionary from df1 where data as keys, emp as values:

Make data as index in the Dataframe then transforme into dict

df1_dict = df1.set_index('data').to_dict()['emp']

Replace values in of name column of df2

df2['name'] = df2['name'].replace(df1_dict)

output:

  ID name
0  u    s
1  v   pp
2  w   ss
3  x    t

Upvotes: 1

Related Questions