Tip*_*ena 5 python sorting indexing concatenation pandas
我试图连接两个 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])
Run Code Online (Sandbox Code Playgroud)
使用pd.concat([df, df2])只是将 df2 附加到 df1 的末尾。我试图将它们连接起来以产生正确的索引顺序(0 到 9)。
jez*_*ael 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
Run Code Online (Sandbox Code Playgroud)