使用`pandas.contat()`完成`A.merge(B).merge(C).merge(D)..`



我有几十个数据帧,如下所示:

import pandas as pd
import numpy as np
A = pd.DataFrame({'col1': np.random.rand(5) ,'col2': np.random.rand(5)})
A.index = [11111, 22222, 33333, 44444, 55555]
B = pd.DataFrame({'col3': np.random.rand(5) ,'col4': np.random.rand(5)})
B.index = [77777, 22222, 33333, 55555, 88888

]

我想对指数做一个外部联接。我可以使用以下A.merge(B)获得所需的结果:

A.merge(B, how='outer', left_index=True, right_index=True)

产生

col1      col2      col3      col4
11111  0.195266  0.765243       NaN       NaN
22222  0.524872  0.978260  0.769246  0.318719
33333  0.581588  0.391997  0.962788  0.864938
44444  0.490709  0.082014       NaN       NaN
55555  0.339119  0.807546  0.545300  0.378834
77777       NaN       NaN  0.345498  0.634918
88888       NaN       NaN  0.976489  0.871800

这就是我想要的。不幸的是,对于大型数据帧,.merge()速度非常慢,在本网站的其他地方,我读到应该使用pd.concat()。但在这种情况下,pd.concat([A, B])不起作用,因为它不接受left_indexright_index关键字。相反,它只是将两者叠加在一起:

col1      col2      col3      col4
11111  0.195266  0.765243       NaN       NaN
22222  0.524872  0.978260       NaN       NaN
33333  0.581588  0.391997       NaN       NaN
44444  0.490709  0.082014       NaN       NaN
55555  0.339119  0.807546       NaN       NaN
77777       NaN       NaN  0.345498  0.634918
22222       NaN       NaN  0.769246  0.318719
33333       NaN       NaN  0.962788  0.864938
55555       NaN       NaN  0.545300  0.378834
88888       NaN       NaN  0.976489  0.871800

有没有一种方法可以使用pd.concat()来实现此联接?还是我被merge卡住了?

只需使用axis=1更改要连接的轴,默认为0:

C = pd.concat([A, B], axis=1)
print(C)

输出如下:

col1      col2      col3      col4
11111  0.707499  0.644641       NaN       NaN
22222  0.971488  0.320773  0.528505  0.257957
33333  0.173358  0.244919  0.899253  0.305035
44444  0.544763  0.101368       NaN       NaN
55555  0.160257  0.456790  0.834480  0.889750
77777       NaN       NaN  0.339059  0.968170
88888       NaN       NaN  0.315871  0.984425

有关如何合并的更多详细信息,您可以查看官方文档:

https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

最新更新