Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing keys for values in dataframe

Tags:

pandas

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 
like image 984
JamesHudson81 Avatar asked May 30 '26 14:05

JamesHudson81


1 Answers

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
like image 133
jezrael Avatar answered Jun 02 '26 14:06

jezrael