You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于索引序号拼接pandas dataframe并按升序保留对应位置

Pandas多DataFrame拼接后按索引升序排列实现方案

问题原因

pd.concat()默认按传入的DataFrame顺序直接拼接,不会自动调整索引排序。你之前调用sort_values()未生效,是因为该方法用于按指定列的数值排序,无法对索引进行排序操作。

实现方法

直接在拼接后调用sort_index()方法即可实现按索引值升序排列:

result = pd.concat([traindf, testdf]).sort_index()

运行后得到的结果符合预期,格式如下:

Class  Sex  SibSp Fare
0     0    0      0     0
1     1    1      1     1
2     2    2      2     2
3     3    3      3     3
4     4    4      4     4
5     5    5      5     5

可选拓展

如果不需要保留原有索引,想要生成全新的连续整数索引,可以额外调用reset_index(),传入drop=True参数丢弃原有索引:

result = pd.concat([traindf, testdf]).sort_index().reset_index(drop=True)

内容的提问来源于stack exchange,提问作者Junaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:18:05