外部根据索引连接两个数据帧,而不中断两个数据帧的原始顺序

2024-10-03 09:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我打算创建一个表来比较两个数据帧的内容。索引是流程的一部分,顺序已预定义。我的数据帧如下所示:

df1:

^{tb1}$

df2:

^{tb2}$

预期合并输出:

^{tb3}$

我尝试了两个指数的并集,即

index_all = df1.index.union(df2.index, sort=False)

然而,这些指数被分类为 |索引1 |索引2 |内容1 |内容2 | ------| ------- | -------- | -------- |xxa | xxa | 0 | 1 |初始|初始| 1 | 1 |泰伊| | 2| |ddas | | 3| |gsdj | gsdj | 4 | 6 |哈斯夫|哈斯夫| 5 | 5 || fafa | 6 || eafa | 7


Tags: 数据内容index顺序流程all指数df1
2条回答

像这样的东西怎么样:

df = pd.DataFrame(index = pd.concat([df1, df2])["Index"].unique(), columns = ["Index1", "Index2"])

df["Index1"] = df1.set_index("Index", drop = False)
df["Index2"] = df2.set_index("Index", drop = False)

df.sort_index().reset_index(drop = True)
#  Index1 Index2
#0      a      a
#1      b      b
#2      c    NaN
#3      d    NaN
#4    NaN      e
#5    NaN      f
#6      g      g
#7      h      h

设置

df1 = pd.DataFrame({'Col1': 1, 'Col2': 2}, [*'abcdgh'])
df2 = pd.DataFrame({'Col3': 3, 'Col4': 4}, [*'abefgh'])

join

使用outer

df1.join(df2, how='outer')

   Col1  Col2  Col3  Col4
a   1.0   2.0   3.0   4.0
b   1.0   2.0   3.0   4.0
c   1.0   2.0   NaN   NaN
d   1.0   2.0   NaN   NaN
e   NaN   NaN   3.0   4.0
f   NaN   NaN   3.0   4.0
g   1.0   2.0   3.0   4.0
h   1.0   2.0   3.0   4.0

相关问题 更多 >