gpt4 book ai didi

python - 连接几个 Pandas 数据框

转载 作者:行者123 更新时间:2023-12-05 04:27:36 25 4
gpt4 key购买 nike

df1 = pd.DataFrame({'a':['id1','id2','id3'],'b':['W','W','W'],'c1':[1,2,3]})
df2 = pd.DataFrame({'a':['id1','id2','id3'],'b':['W','W','W'],'c2':[4,5,6]})
df3 = pd.DataFrame({'a':['id1','id4','id5'],'b':['Q','Q','Q'],'c1':[7,8,9]})

我正在尝试将 df1 df2df3 连接到一个数据帧中:

a    b   c1   c2
id1 W 1 4
id2 W 2 5
id3 W 3 6
id1 Q 7 NA
id4 Q 8 NA
id5 Q 9 NA

我试过:

l = [d.set_index(['a','b']) for d in [df1,df2,df3]]
pd.concat(l, axis=1)

但输出不是我所期望的:

        c1   c2   c1
a b
id1 W 1.0 4.0 NaN
id2 W 2.0 5.0 NaN
id3 W 3.0 6.0 NaN
id1 Q NaN NaN 7.0
id4 Q NaN NaN 8.0
id5 Q NaN NaN 9.0

最佳答案

您可以加入由DataFrame.stack 创建的MultiIndex 系列 :

l = [d.set_index(['a','b']).stack() for d in [df1,df2,df3]]
df = pd.concat(l).unstack().sort_index(level=[1,0], ascending=[False, True])
print (df)
c1 c2
a b
id1 W 1.0 4.0
id2 W 2.0 5.0
id3 W 3.0 6.0
id1 Q 7.0 NaN
id4 Q 8.0 NaN
id5 Q 9.0 NaN

如果只有 3 列 DataFrames 使用 DataFrame.squeeze或通过 iloc[:, 0] 选择第一列作为系列列表:

l = [d.set_index(['a','b']).squeeze() for d in [df1,df2,df3]]
keys = [x.name for x in l]
df = (pd.concat(l, axis=0, keys=keys)
.unstack(0)
.sort_index(level=[1,0], ascending=[False, True]))
print (df)
c1 c2
a b
id1 W 1.0 4.0
id2 W 2.0 5.0
id3 W 3.0 6.0
id1 Q 7.0 NaN
id4 Q 8.0 NaN
id5 Q 9.0 NaN

l = [d.set_index(['a','b']).iloc[:, 0] for d in [df1,df2,df3]]
keys = [x.name for x in l]
df = (pd.concat(l, axis=0, keys=keys)
.unstack(0)
.sort_index(level=[1,0], ascending=[False, True]))

另一个想法是通过 DataFrame.combine_first 在列表中链接多个 DataFrame。 :

from functools import reduce

dfs = [d.set_index(['a','b']) for d in [df1,df2,df3]]
df = (reduce(lambda x, y: x.combine_first(y), dfs)
.sort_index(level=[1,0], ascending=[False, True]))
print (df)
c1 c2
a b
id1 W 1.0 4.0
id2 W 2.0 5.0
id3 W 3.0 6.0
id1 Q 7.0 NaN
id4 Q 8.0 NaN
id5 Q 9.0 NaN

关于python - 连接几个 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72784509/

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