假设我有 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
(“一”、“二”、“三”、“四”)组成,下一列由名称组成,其中我想更改df
数据框的列名。
我怎样才能用一行/两行代码在熊猫中做到这一点?
您需要rename
通过dict
或通过Series
:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句