如何将两个数据帧合并为一个,同时对两个数据帧的所有行和所有索引值进行 keping ?
假设我有两个数据帧,其索引值部分不同:
df1 = pd.DataFrame(np.random.randn(5, 1), columns=['a'], index=[0, 2, 3, 4, 5])
df2 = pd.DataFrame(np.random.randn(5, 1), columns=['b'], index=[1, 2, 3, 4, 6])
a
0 -1.089084
2 -0.552297
3 -0.242239
4 0.247463
5 -0.139740
b
1 -0.407245
2 1.704591
3 -0.803438
4 -1.511515
6 0.303360
我想创建一个新的数据帧,其中包含具有组合索引的两列。我试过了:
df_combine = pd.DataFrame()
df_combine['a'] = df1['a']
df_combine['b'] = df2['b']
这导致:
a b
0 -1.089084 NaN
2 -0.552297 1.704591
3 -0.242239 -0.803438
4 0.247463 -1.511515
5 -0.139740 NaN
在我想要的地方,保留所有行和索引值,如果此索引值没有可用的值,则使用 NaN:
a b
0 -1.089084 NaN
1 NaN -0.407245
2 -0.552297 1.704591
3 -0.242239 -0.803438
4 0.247463 -1.511515
5 -0.139740 NaN
6 NaN 0.303360
试试 pandas.concat 函数: https://pandas.pydata.org/pandas-docs/stable/merging.html
dd = pd.concat([df1, df2], axis=1)
print(dd)
输出:
a b
0 -0.603074 NaN
1 NaN -0.021821
2 0.501050 0.342474
3 -2.612637 -0.256383
4 0.095779 -1.423016
5 -0.644108 NaN
6 NaN -1.756023