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

如何直接从列表/元组创建Multi-Index(多层索引)DataFrame?

如何直接从列表/元组创建Multi-Index(多层索引)DataFrame?

当然有办法直接创建!你当前的方法完全可行,但确实可以跳过先建普通DataFrame再设置索引的步骤,直接从你的列表生成多层索引的DataFrame。这里有两种简洁的实现方式:

方法一:拆分数据并显式构建MultiIndex

你可以把每行数据拆分为索引部分和值部分,用pd.MultiIndex.from_tuples提前构建好多层索引,再直接传入DataFrame构造函数:

import pandas as pd

data = [["Machine","Car","Sedan",10], ["Machine","Bike","2 Wheel",5], ["Machine","Bike","3 Wheel",4], ["Animal","Donkey","Big",2]]

# 提取每行前三个元素作为索引元组,第四个元素作为值
index_tuples = [tuple(row[:3]) for row in data]
values = [row[3] for row in data]

# 定义各索引层级的名称
index_names = ["Category", "Sub Category", "Sub Sub Category"]

# 创建多层索引对象
multi_index = pd.MultiIndex.from_tuples(index_tuples, names=index_names)

# 直接生成带多层索引的DataFrame
df = pd.DataFrame(values, index=multi_index, columns=["Value"])

方法二:紧凑的合并写法

如果喜欢更简洁的代码,也可以把所有步骤合并成一段(依然保持可读性):

import pandas as pd

data = [["Machine","Car","Sedan",10], ["Machine","Bike","2 Wheel",5], ["Machine","Bike","3 Wheel",4], ["Animal","Donkey","Big",2]]

df = pd.DataFrame(
    [row[3] for row in data],
    index=pd.MultiIndex.from_tuples(
        [tuple(row[:3]) for row in data],
        names=["Category", "Sub Category", "Sub Sub Category"]
    ),
    columns=["Value"]
)

原理说明

多层索引(MultiIndex)的核心是由一系列元组组成的,每个元组对应一行的完整索引路径。我们通过提取每行前三个元素并转为元组,直接构建出这个索引结构,再把第四个元素作为值列,这样就省去了后续调用set_index的步骤。如果你的原始数据本身就是元组格式(比如("Machine", "Car", "Sedan", 10)),那连tuple()转换都可以省略,直接用row[:3]即可。

备注:内容来源于stack exchange,提问作者Tim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 18:48:11