2017-07-03 70 views
1

假设我有4列中的数据帧:重命名使用其它数据帧中大熊猫列

df = pd.DataFrame({'one': [1., 2., 3., 4.], 
    'two': [4., 3., 2., 1.], 
    'three': [4., 3., 2., 1.], 
    'four': [4., 3., 2., 1.]}) 

和假设有另一个数据帧(2列): 第一列包括列的名称的的数据帧df('one','two','three','four'),下一列由名称组成,我想要将其更改为df数据帧的列名。

我该如何在一两行代码中完成熊猫?

回答

2

您需要rename通过dictSeries

print (df1) 
     a b 
0 one c 
1 two d 
2 three e 
3 four f 

d = df1.set_index('a')['b'].to_dict() 
#by Series 
#d = df1.set_index('a')['b'] 
print (d) 
{'four': 'f', 'two': 'd', 'three': 'e', 'one': 'c'} 

df = pd.DataFrame({'one': [1., 2., 3., 4.], 
    'two': [4., 3., 2., 1.], 
    'three': [4., 3., 2., 1.], 
    'four': [4., 3., 2., 1.]}) 
print (df) 

df = df.rename(columns=d) 
print (df) 
    f c e d 
0 4.0 1.0 4.0 4.0 
1 3.0 2.0 3.0 3.0 
2 2.0 3.0 2.0 2.0 
3 1.0 4.0 1.0 1.0 
+0

完美,谢谢! –

+0

很高兴能帮到你!您也可以注册 - 点击接受标记上方'0'上方的小三角。谢谢。 – jezrael