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

如何指定level1-level4值,获取pandas多层索引DataFrame的level0索引值

实现方案

通过pandas的自定义索引访问器即可实现你需要的调用效果,完整代码如下:

import pandas as pd
import numpy as np

# 注册自定义的MultiIndex访问器
@pd.api.extensions.register_index_accessor("Magic_command")
class MagicCommandAccessor:
    def __init__(self, index):
        self._index = index
        if not isinstance(index, pd.MultiIndex):
            raise TypeError("仅支持MultiIndex使用该访问器")
    
    def __getitem__(self, items):
        if not isinstance(items, tuple):
            items = (items,)
        # 不足层级的部分自动补全为全选
        if len(items) < self._index.nlevels:
            items = items + tuple([slice(None)] * (self._index.nlevels - len(items)))
        if len(items) > self._index.nlevels:
            raise ValueError(f"参数长度不能超过索引层级数,当前索引共{self._index.nlevels}层")
        
        # 定位要返回的目标层级(None对应的位置)
        target_level = None
        filter_conditions = []
        for level_idx, val in enumerate(items):
            if val is None:
                if target_level is not None:
                    raise ValueError("仅允许传入一个None标记目标返回层级")
                target_level = level_idx
                filter_conditions.append(slice(None))
            else:
                filter_conditions.append(val)
        
        if target_level is None:
            raise ValueError("需传入一个None标记要返回的层级位置")
        
        # 过滤匹配的索引,提取目标层级的结果
        filtered_idx = self._index.get_loc(tuple(filter_conditions))
        res = self._index[filtered_idx].get_level_values(target_level).unique()
        return res[0] if len(res) == 1 else res

# 构造示例DataFrame
arr = [np.array(['car', 'car', 'car','car', 'car', 'car', 'car', 'car', 'car', 'truck', 'truck', 'truck', 'truck', 'truck', 'truck','truck', 'truck', 'truck','bike','bike', 'bike','bike','bike', 'bike','bike','bike', 'bike']),
       np.array(['valueA', 'valueA','valueA', 'valueA','valueA', 'valueA','valueA', 'valueA','valueA','valueB','valueB','valueB','valueB','valueB','valueB','valueB','valueB','valueB', 'valueC','valueC','valueC','valueC','valueC','valueC','valueC','valueC','valueC']),
       np.array(['row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row','row']),
       np.array(['p1','p1','p1','p2','p2','p2','p3','p3','p3','p1','p1','p1','p2','p2','p2','p3','p3','p3','p1','p1','p1','p2','p2','p2','p3','p3','p3',]),
       np.array(['1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3',])]

dataFrame = pd.DataFrame(
   np.random.randn(27, 3), index=arr,columns=['Col 1', 'Col 2', 'Col 3'])
dataFrame.index.names = ['level 0', 'level 1','level 2','level 3','level 4']

# 测试示例
print(dataFrame.index.Magic_command[None,'valueA','row','p1'])
# 输出:car
print(dataFrame.index.Magic_command[None,'valueC','row','p1','1'])
# 输出:bike

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:04