gpt4 book ai didi

python - 在保持索引顺序的同时连接两个 Pandas DataFrame

转载 作者:太空宇宙 更新时间:2023-11-04 01:53:12 24 4
gpt4 key购买 nike

基本问题 - 我正在尝试连接两个 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)。

最佳答案

使用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

关于python - 在保持索引顺序的同时连接两个 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57533867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com