2017-10-21 103 views
1

我有3个df,每个列有25个列。所有列在3 df中都是相同的。合并3个相同名称的数据库,并将它们重命名为python

我想合并三个df,并将25列df1的列名更改为“_a”,将25列df2更改为“_b”,将25列df3更改为“_c”。

我使用下面的代码:

pd.merge(pd.merge(df1,df2,'left',on='year',suffixes=['_a','_b']),df3,'left',on='year') 

如何使用重命名或其他一些功能,改变在上面的代码中所有DF3的25列?

谢谢。

回答

2
pd.merge(pd.merge(df1,df2,'left',on='year',suffixes=['_a','_b']), 
     df3,'left',on='year',suffixes=['','_c']) 

另一种方法:

来源的DF:

In [68]: d1 
Out[68]: 
    col1 col2 col3 
0  1  2  3 
1  4  5  6 

In [69]: d2 
Out[69]: 
    col1 col2 col3 
0 11 12 13 
1 14 15 16 

In [70]: d3 
Out[70]: 
    col1 col2 col3 
0 21 22 23 
1 24 25 26 

让我们创建的DFS列表:

In [71]: dfs = [d1,d2,d3] 

和后缀的列表:

In [73]: suffixes = ['_a','_b','_c'] 

现在我们可以像如下一步到位将它们合并:

In [74]: pd.concat([df.add_suffix(suffixes[i]) for i,df in enumerate(dfs)], axis=1) 
Out[74]: 
    col1_a col2_a col3_a col1_b col2_b col3_b col1_c col2_c col3_c 
0  1  2  3  11  12  13  21  22  23 
1  4  5  6  14  15  16  24  25  26 

简短的解释:列表中的理解,我们正在生成的DFS与已经改名列的列表:

In [75]: [suffixes[i] for i,df in enumerate(dfs)] 
Out[75]: ['_a', '_b', '_c'] 

In [76]: [df.add_suffix(suffixes[i]) for i,df in enumerate(dfs)] 
Out[76]: 
[ col1_a col2_a col3_a 
0  1  2  3 
1  4  5  6, col1_b col2_b col3_b 
0  11  12  13 
1  14  15  16, col1_c col2_c col3_c 
0  21  22  23 
1  24  25  26] 
+0

伟大的演示,甚至在编辑之前! [列表理解](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)经常让那些新加入Python的人感到困惑,所以他们通常应该得到一个小小的解释或说明。尽管如此,你的回答是清晰而简洁的。 +1 – Aaron3468

+0

@ Aaron3468,谢谢!我已经添加了一个简短的解释... – MaxU

+0

谢谢! 'd','left',on ='year',后缀= ['_ a','_ b']), ['','_ c'])不起作用,因为我猜数据框的列应该是相同的(注意合并2个dfs将列更改为“_a”和“_b”,因此它们与df3不同。如何使用重命名函数来更改第三个df的后缀? – Andrew

相关问题