使用相似和不相交的列连接DataFrame

问题描述 投票:1回答:1

为简化讨论,简化了问题。

取3个具有相似和不相交列的数据帧,但列值相同。如何以没有重复列的方式连接它们,保留所有唯一列(即不进行内连接),如果列值相同,则不会创建新行?

个别数据框:

DF1:

    a  b  c
0   1  2  3
1  11 22 33

DF2:

    b  c  d
0   2  3  4
1  22 33 44

付款方式:

    c  d  e
0   3  4  5
1  33 44 55

期望的输出:

    a   b   c   d   e
0   1   2   3   4   5
1  11  22  33  44  55

但是,只需使用

pd.concat([df1, df2, df3], axis=1)

包括重复列。

python join dataframe concatenation
1个回答
1
投票

选项1 使用concat + groupby -

pd.concat([df1, df2, df3], 1).groupby(axis=1, level=0).first()

    a   b   c   d   e
0   1   2   3   4   5
1  11  22  33  44  55

选项2 merge -

df1.merge(df2).merge(df3)

    a   b   c   d   e
0   1   2   3   4   5
1  11  22  33  44  55

通常,对于n数据帧,如果您有一个列表,您可以执行与循环的n路合并 -

df_list = [df1, df2, df3]
df = df_list[0]

for d in df_list[1:]:
    df = df.merge(d)

df
    a   b   c   d   e
0   1   2   3   4   5
1  11  22  33  44  55
© www.soinside.com 2019 - 2024. All rights reserved.