Replacing keys for values ββin a dataframe
I have 2 dictionaries
dict1={'Water': 'H2O', 'Lithium': 'L'}
dict2={'five': 'pentagon', 'eight': 'Octagon'}
And the next information frame
Water five Lithium eight
Chemical tests
test1 26.87 25.06 26.79 15.23
test2 6.06 3.21 4.16 1.46
test3 -- 4.11 8.61 2.16
test4 20.25 36.22 20.94 58.86
I was wondering if there is an option to change the header of each column to the corresponding value in 2 dictionaries.
The desired output will look something like this:
H20 pentagon L octagon
Chemical tests
test1 26.87 25.06 26.79 15.23
test2 6.06 3.21 4.16 1.46
test3 -- 4.11 8.61 2.16
test4 20.25 36.22 20.94 58.86
+3
source to share
1 answer
Use double rename
:
df = df.rename(columns=dict1).rename(columns=dict2)
print (df)
H2O pentagon L Octagon
Chemical tests
test1 26.87 25.06 26.79 15.23
test2 6.06 3.21 4.16 1.46
test3 -- 4.11 8.61 2.16
test4 20.25 36.22 20.94 58.86
Or combine it dict
into one:
z = dict1.copy()
z.update(dict2)
df = df.rename(columns=z)
print (df)
H2O pentagon L Octagon
Chemical tests
test1 26.87 25.06 26.79 15.23
test2 6.06 3.21 4.16 1.46
test3 -- 4.11 8.61 2.16
test4 20.25 36.22 20.94 58.86
+2
source to share