使用 pandas 在两个数据框中连接不同的列(并追加相似的列) [英] Concatenate distinct columns in two dataframes using pandas (and append similar columns)
问题描述
我的问题与> Pandas Merge-如何避免重复的列 但不完全相同.
我要串联三个数据帧中不同的列.数据框具有一个列ID,以及一些相同的列:例如.
I want to concatenate the columns that are different in three dataframes. The dataframes have a column id, and some columns that are identical: Ex.
df1
id place name qty unit A
1 NY Tom 2 10 a
2 TK Ron 3 15 a
3 Lon Don 5 90 a
4 Hk Sam 4 49 a
df2
id place name qty unit B
1 NY Tom 2 10 b
2 TK Ron 3 15 b
3 Lon Don 5 90 b
4 Hk Sam 4 49 b
df3
id place name qty unit C D
1 NY Tom 2 10 c d
2 TK Ron 3 15 c d
3 Lon Don 5 90 c d
4 Hk Sam 4 49 c d
结果:
id place name qty unit A B C D
1 NY Tom 2 10 a b c d
2 TK Ron 3 15 a b c d
3 Lon Don 5 90 a b c d
4 Hk Sam 4 49 a b c d
列的位置,名称,数量和单位将始终是三个数据框的一部分,不同的列名称可能会有所不同(在我的示例中为A,B,C,D).这三个数据框具有相同的行数.
The columns place, name, qty, and unit will always be part of the three dataframes, the names of columns that are different could vary (A,B,C,D in my example). The three dataframes have the same number of rows.
我尝试过:
cols_to_use = df1.columns - df2.columns
dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')
问题是我得到的行比预期的多,并且在结果数据框中重命名了列(使用concat时).
The problem is that I get more rows than expected and columns renamed in the resulting dataframe (when using concat).
推荐答案
使用functools
from functools import reduce
reduce(lambda left,right: pd.merge(left,right), [df1,df2,df3])
Out[725]:
id place name qty unit A B C D
0 1 NY Tom 2 10 a b c d
1 2 TK Ron 3 15 a b c d
2 3 Lon Don 5 90 a b c d
3 4 Hk Sam 4 49 a b c d
这篇关于使用 pandas 在两个数据框中连接不同的列(并追加相似的列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!