根据字典重命名PANDAS中的列 [英] Rename columns in PANDAS based on dictionary
本文介绍了根据字典重命名PANDAS中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,我想根据我打算用作字典的另一个数据框重命名列.例如,我拥有的第一个数据框是:
AAA BBB CCC DDD
index
1 1 2 3 4
2 5 6 7 8
以及作为我想用作字典的第二个数据框:
val1 val2
index
1 AAA A7
2 BBB B0
3 CCC C3
4 DDD D1
我想要得到的结果如下:
A7 B0 C3 D1
index
1 1 2 3 4
2 5 6 7 8
最初,我想将第一个数据框重塑为长格式,然后与字典数据框合并,然后重塑为宽格式.但是我认为这效率很低,因此我想使用一种更有效的方法(如果存在).非常感谢您的帮助.
我认为您可以首先从df2
创建dictionary
,然后通过Series
. //pandas.pydata.org/pandas-docs/stable/generation/pandas.Index.to_series.html"rel =" noreferrer> to_series
然后您 解决方案 I think you can first create dictionary
from df2
, then create Series
from columns of df1
by to_series
which you then map
using dictionary
:
print df1
AAA BBB CCC DDD
index
1 1 2 3 4
2 5 6 7 8
print df2
val1 val2
index
1 AAA A7
2 BBB B0
3 CCC C3
4 DDD D1
d = df2.set_index('val1').to_dict()
print d['val2']
{'AAA': 'A7', 'BBB': 'B0', 'CCC': 'C3', 'DDD': 'D1'}
df1.columns = df1.columns.to_series().map(d['val2'])
print df1
A7 B0 C3 D1
index
1 1 2 3 4
2 5 6 7 8
这篇关于根据字典重命名PANDAS中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文