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

如何编写通用函数实现pandas DataFrame末位索引移至首位的重索引

pandas将最后一个索引移至首位的通用实现

核心思路

你需要的0到倒数第二位的连续索引不需要手动枚举,直接用Python内置的range(len(obj)-1)就能自动生成,拼接上最后一个索引值len(obj)-1即可得到任意长度下的目标索引序列。

通用函数实现

针对默认0基连续索引的DataFrame/Series,可直接封装为如下复用函数:

import pandas as pd

def reorder_last_to_first(obj):
    """
    重排0基连续索引的pandas对象,将最后一个索引位置的元素移动到首位
    参数: obj - pandas.DataFrame 或 pandas.Series,要求索引为从0开始的连续整数
    返回: 重排后的同类型pandas对象
    """
    total_len = len(obj)
    # 拼接目标索引:最后一位索引 + 0到倒数第二位的连续索引
    target_idx = [total_len - 1] + list(range(total_len - 1))
    return obj.reindex(index=target_idx)

测试验证

使用你提供的测试代码运行,结果和手动指定索引的预期输出完全一致:

# 测试用例1
a = pd.DataFrame({'geo':['Nation', 'geo1', 'geo2', 'geo3', 'geo4', 'geo5', 'geo6', 'county']})
print(reorder_last_to_first(a.geo))

# 测试用例2
b = pd.DataFrame({'geo':['Nation', 'geo1', 'geo2', 'geo3', 'geo4',  'county']})
print(reorder_last_to_first(b.geo))

输出:

7    county
0    Nation
1      geo1
2      geo2
3      geo3
4      geo4
5      geo5
6      geo6
Name: geo, dtype: object

5    county
0    Nation
1      geo1
2      geo2
3      geo3
4      geo4
Name: geo, dtype: object

更鲁棒的优化版本

如果你的处理对象索引不是默认0基连续值(比如是日期、字符串、非连续整数索引),reindex方案会失效,可以改用按位置选取的实现,不依赖原有索引取值,适配所有pandas对象:

import pandas as pd
import numpy as np

def move_last_row_to_first(obj):
    total_len = len(obj)
    # np.r_用于拼接位置索引数组,按位置选取行
    return obj.iloc[np.r_[total_len - 1, 0:total_len - 1]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.20 16:15:48