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

Pandas中[::-1]索引的含义是什么?已知[:,-1]取所有行最后一列

Pandas中[::-1]索引的含义解释

[::-1]是继承自Python原生的切片语法,在Pandas里主要用来反转数据的顺序,具体表现根据数据类型略有不同:

  • 对于一维的Series:
    会将整个序列的元素(包括对应的索引)完全倒序排列。比如原Series是按顺序存储的数值,使用[::-1]后会从最后一个元素开始往前取所有值。
    示例代码:

    import pandas as pd
    s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd'])
    reversed_s = s[::-1]
    # 输出结果:
    # d    40
    # c    30
    # b    20
    # a    10
    # dtype: int64
    
  • 对于二维的DataFrame:
    会反转整个数据框的行顺序,列的顺序保持不变,行索引也会跟着倒序排列。
    示例代码:

    import pandas as pd
    df = pd.DataFrame({'Col1': [1, 2, 3], 'Col2': ['x', 'y', 'z']})
    reversed_df = df[::-1]
    # 输出结果:
    #    Col1 Col2
    # 2     3    z
    # 1     2    y
    # 0     1    x
    

本质上,[::-1]是切片语法[start:end:step]的简写:start默认取序列末尾位置,end默认取序列开头位置,step设为-1表示从后往前遍历,最终实现整体反转的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:05:23