连接两个 Pandas DataFrame 同时保持索引顺序

问题描述 投票:0回答:2

我正在尝试连接两个 DataFrame,生成的 DataFrame 按原始两个 DataFrame 的顺序保留索引。例如:

df = pd.DataFrame({'Houses':[10,20,30,40,50], 'Cities':[3,4,7,6,1]}, index = [1,2,4,6,8])


df2 = pd.DataFrame({'Houses':[15,25,35,45,55], 'Cities':[1,8,11,14,4]}, index = [0,3,5,7,9])

使用

pd.concat([df, df2])
只需将 df2 附加到 df1 的末尾。我尝试将它们连接起来以产生正确的索引顺序(0 到 9)。

python pandas sorting indexing concatenation
2个回答
10
投票

使用

concat
和参数
sort
以避免警告,然后
DataFrame.sort_index
:

df = pd.concat([df, df2], sort=False).sort_index()

print(df)
   Cities  Houses
0       1      15
1       3      10
2       4      20
3       8      25
4       7      30
5      11      35
6       6      40
7      14      45
8       1      50
9       4      55

0
投票

尝试使用:

print(df.T.join(df2.T).T.sort_index())

输出:

   Cities  Houses
0       1      15
1       3      10
2       4      20
3       8      25
4       7      30
5      11      35
6       6      40
7      14      45
8       1      50
9       4      55
© www.soinside.com 2019 - 2024. All rights reserved.