gpt4 book ai didi

python - 将 DataFrame 与相似和不相交的列连接起来

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:07 30 4
gpt4 key购买 nike

为了便于讨论,问题被简化。

取 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

df3:

    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)

包括重复的列。

最佳答案

选项 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
合并 -

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

关于python - 将 DataFrame 与相似和不相交的列连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47871328/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com