Python – Replaces values in pandas data frames with nested dictionaries

Replaces values in pandas data frames with nested dictionaries… here is a solution to the problem.

Replaces values in pandas data frames with nested dictionaries

I have the following data frame and dictionary:

df = pd. DataFrame([{'A': 'a', 'B': 'a', 'C': 'a'}, {'A': 'b', 'B': 'b', 'C': 'b'}], columns=["A", "B", "C"])
df

A    B    C
 0   a    a    a
 1   b    b    b

dic = { 'A': { 'a': 'label aa', 'b': 'label aaa'}, 'B': { 'a': 'label bb', 'b': 'label bbb'}, 'C': { 'a': 'label cc', 'b': 'label ccc'}}
dic

{'A': {'a': 'label aa', 'b': 'label aaa'},
 'B': {'a': 'label bb', 'b': 'label bbb'},
 'C': {'a': 'label cc', 'b': 'label ccc'}}

I want to match the df column with the “foreign key”. Once a match is found, I want to map the row with the “value of the internal key”.

This is the result I want :

     A           B          C
0  label aa   label bb   label cc
1  label aaa  label bbb  label ccc

Solution

You are looking for replace, your dictionary has been created, the first key matches the column, and the second matches the value to be replaced, then this value is the to_replace value

df.replace(dic)
Out[764]: 
           A          B          C
0   label aa   label bb   label cc
1  label aaa  label bbb  label ccc

Related Problems and Solutions