在数据框中将键替换为值

3
我有两个字典。
dict1={'Water''H2O',  'Lithium''L'}

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

以下是数据框(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 

我想知道是否有可能通过2个字典中相应的值来更改每个列标题。
期望的输出如下所示。
                     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 
1个回答

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

或者将两个字典合并成一个:

合并这两个dict

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接