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

如何遍历Pandas DataFrame的条目?含多索引DataFrame示例

遍历多索引Pandas DataFrame的实用方法

嘿,针对你给出的这个多索引DataFrame,我整理了几个实用的遍历每个元素的方法,结合示例来一步步说,方便你上手:

首先先把你的示例代码放出来,确保大家能复现这个DataFrame:

import pandas as pd
import numpy as np

iterables = [['foo', 'bar'], ['one', 'two']]
idx = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(4, 2), index=idx, columns=('metric1', 'metric2'))

方法1:用stack()转成Series后遍历(最省心的方式)

把DataFrame堆叠成一个带三层索引的Series,这样每个元素的多索引+列名都被整合到一起,遍历的时候直接就能拿到所有信息:

stacked_series = df.stack()
for (first, second, metric), value in stacked_series.items():
    print(f"索引:first={first}, second={second}, 指标={metric},值:{value:.6f}")

这种方法完全不用自己拆分索引,输出的信息完整又清晰,我个人平时用得最多~

方法2:用iterrows()先遍历行,再遍历元素

iterrows()会返回每行的多索引元组和整行数据,拿到行之后再遍历行里的每个指标值:

for (first, second), row in df.iterrows():
    for metric, value in row.items():
        print(f"索引:first={first}, second={second}, 指标={metric},值:{value:.6f}")

这个方法适合需要先对整行做一些预处理,再细化到每个元素的场景,逻辑上更贴合“先行后列”的思路。

方法3:用itertuples()(大数据量首选)

如果你的DataFrame数据量很大,那itertuples()会比iterrows()高效不少,它返回的是命名元组,我们可以直接提取多索引和各列的值:

for row_tuple in df.itertuples():
    # row_tuple.Index就是多索引的元组,后面跟着各列的数值
    first, second = row_tuple.Index
    print(f"first={first}, second={second}, metric1={row_tuple.metric1:.6f}, metric2={row_tuple.metric2:.6f}")

不过这个方法需要你提前知道列名,适合列固定不变的场景,速度优势在数据量上去之后会特别明显。

方法4:用applymap()隐式遍历(无显式循环)

如果你不想写显眼的for循环,可以用applymap()给每个元素绑定一个自定义函数,比如用来打印元素信息:

def process_element(value):
    # 通过stack后的Series找到当前元素的完整索引
    full_idx = df.stack()[df.stack() == value].index[0]
    print(f"索引:first={full_idx[0]}, second={full_idx[1]}, 指标={full_idx[2]},值:{value:.6f}")

df.applymap(process_element)

注意哦,这个方法如果DataFrame里有重复值会出错,更适合处理值唯一的场景,或者你只需要处理元素本身的情况。

其实大多数遍历方法的核心都是如何获取元素对应的完整索引信息,你可以根据自己的需求——比如要不要索引、数据量大小、代码简洁性——来选最合适的方法~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:56:44