2017-05-18 133 views
3

我有2個字典替換密鑰值數據幀

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

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

而下面的數據幀

     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  

我想知道是否有通過其相應的值在改變每個列標題的可能性這兩本字典。

所需的輸出會是這個樣子

     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  

回答

2

使用雙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 

或者mergedict s到一個:

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