根据行顺序连接两个 pandas 数据帧
Join two pandas dataframes based on line order
我有两个数据帧 df1 和 df2 我想加入。它们的索引不相同,并且它们没有任何公共列。我想要的是根据行的顺序连接它们,即连接 df1 的第一行和 df2 的第一行,连接 df1 的第二行和 df2 的第二行,等等
示例:
df1:
'A' 'B'
0 1 2
1 3 4
2 5 6
df2:
'C' 'D'
0 7 8
3 9 10
5 11 12
应该给
'A' 'B' 'C' 'D'
0 1 2 7 8
3 3 4 9 10
5 5 6 11 12
我不关心最终数据框中的索引。我尝试用 df2 的索引重新索引 df1 但无法使其工作。
我想你可以尝试连接它们(这样做会在索引上执行连接,由于reset_index
,这对于两个 DataFrame 是相同的):
In [18]: df1.join(df2.reset_index(drop=True))
Out[18]:
'A' 'B' 'C' 'D'
0 1 2 7 8
1 3 4 9 10
2 5 6 11 12
您可以分配给 df2
的 df1
索引,然后使用 join
:
df1.index = df2.index
res = df1.join(df2)
In [86]: res
Out[86]:
'A' 'B' 'C' 'D'
0 1 2 7 8
3 3 4 9 10
5 5 6 11 12
或者您可以在一行中使用 set_index
:
In [91]: df1.set_index(df2.index).join(df2)
Out[91]:
'A' 'B' 'C' 'D'
0 1 2 7 8
3 3 4 9 10
5 5 6 11 12
尝试 concat
:
pd.concat([df1.reset_index(), df2.reset_index()], axis=1)
reset_index
() 调用使索引相同,然后,concat
与 axis=1
简单地水平连接。
我有两个数据帧 df1 和 df2 我想加入。它们的索引不相同,并且它们没有任何公共列。我想要的是根据行的顺序连接它们,即连接 df1 的第一行和 df2 的第一行,连接 df1 的第二行和 df2 的第二行,等等
示例:
df1:
'A' 'B'
0 1 2
1 3 4
2 5 6
df2:
'C' 'D'
0 7 8
3 9 10
5 11 12
应该给
'A' 'B' 'C' 'D'
0 1 2 7 8
3 3 4 9 10
5 5 6 11 12
我不关心最终数据框中的索引。我尝试用 df2 的索引重新索引 df1 但无法使其工作。
我想你可以尝试连接它们(这样做会在索引上执行连接,由于reset_index
,这对于两个 DataFrame 是相同的):
In [18]: df1.join(df2.reset_index(drop=True))
Out[18]:
'A' 'B' 'C' 'D'
0 1 2 7 8
1 3 4 9 10
2 5 6 11 12
您可以分配给 df2
的 df1
索引,然后使用 join
:
df1.index = df2.index
res = df1.join(df2)
In [86]: res
Out[86]:
'A' 'B' 'C' 'D'
0 1 2 7 8
3 3 4 9 10
5 5 6 11 12
或者您可以在一行中使用 set_index
:
In [91]: df1.set_index(df2.index).join(df2)
Out[91]:
'A' 'B' 'C' 'D'
0 1 2 7 8
3 3 4 9 10
5 5 6 11 12
尝试 concat
:
pd.concat([df1.reset_index(), df2.reset_index()], axis=1)
reset_index
() 调用使索引相同,然后,concat
与 axis=1
简单地水平连接。