3

I have 2 dictionaries

dict1={'Water': 'H2O',  'Lithium': 'L'}

dict2={'five': 'pentagon', 'eight': 'Octagon'}

And the following dataframe

                     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 was a possibility to change the every column header by its corresponding value in the 2 dictionaries.

The desired output would 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 
JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

1 Answers1

2

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 merge both dicts to 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
Community
  • 1
  • 1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252