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

如何获取Pandas DataFrame多级索引唯一元组及指定行索引值

Pandas多级索引指定行元组提取方案

复现代码

import numpy as np
import pandas as pd

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,100,size=(100, 5)), columns=list('ABCDF'))
df = df.set_index(['A','B','C'])

可用实现方式

  • 直接按位置读取索引对象取值
    DataFrame的index属性存储了所有行对应的索引值,多级索引场景下单个位置的返回值就是包含所有层级索引值的元组,可以直接用于后续跨表查询:
    n = 0 # 替换为你需要取的行位置,注意位置计数从0开始
    target_index = df.index[n]
    
  • 通过iloc取行后读取行名
    如果逻辑中已经先通过位置筛选到了目标行,直接读该行的name属性就能拿到对应索引元组,不需要额外再访问index对象:
    n = 0
    target_row = df.iloc[n]
    target_index = target_row.name
    
  • 批量提取唯一索引元组
    如果需要拿到全表所有不重复的多级索引元组,直接调用索引的去重方法即可:
    unique_index_tuples = df.index.unique()
    
    遍历该返回结果就能逐个拿到无重复的索引元组,不会出现重复取值的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.18 16:15:44