Python 基于要联接的多个数据帧的索引值构造索引
我需要将多个数据帧组合成一个数据帧。它们都有整数索引,我想保留在结果中 例如: df_1 df_2 结果:Python 基于要联接的多个数据帧的索引值构造索引,python,pandas,dataframe,indexing,left-join,Python,Pandas,Dataframe,Indexing,Left Join,我需要将多个数据帧组合成一个数据帧。它们都有整数索引,我想保留在结果中 例如: df_1 df_2 结果: a b 0 1 - 1 3 - 2 - 4 4 - 11 5 10 - 7 2 3 9 - 4 到目前为止,我一直在使用这种方法,我想知道是否有更清洁的解决方案: dfs = [df_1, df_2, ...] join_index = list() for df in dfs: j
a b
0 1 -
1 3 -
2 - 4
4 - 11
5 10 -
7 2 3
9 - 4
到目前为止,我一直在使用这种方法,我想知道是否有更清洁的解决方案:
dfs = [df_1, df_2, ...]
join_index = list()
for df in dfs:
join_index.extend(df.index.tolist())
join_index = sorted(list(set(join_index)))
然后在将数据帧连接在一起时使用join_索引。使用,索引是列表中数据帧
的所有索引的并集,并且还被排序:
dfs = [df_1, df_2]
df = pd.concat(dfs, axis=1)
print (df)
a b
0 1.0 NaN
1 3.0 NaN
2 NaN 4.0
4 NaN 11.0
5 10.0 NaN
7 2.0 3.0
9 NaN 4.0
dfs = [df_1, df_2, ...]
join_index = list()
for df in dfs:
join_index.extend(df.index.tolist())
join_index = sorted(list(set(join_index)))
dfs = [df_1, df_2]
df = pd.concat(dfs, axis=1)
print (df)
a b
0 1.0 NaN
1 3.0 NaN
2 NaN 4.0
4 NaN 11.0
5 10.0 NaN
7 2.0 3.0
9 NaN 4.0