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

Pandas:DataFrame转dict(records)后,如何结合enumerate访问值?

解决DataFrame转字典后结合enumerate获取索引并访问值的问题

问题描述

我现在用df.itertuples()遍历大型DataFrame,但这个方法速度慢,听说转成字典(用df.to_dict('records'))能大幅提升效率。但遇到个问题:怎么结合enumerate获取原索引值,同时访问字典里的列值?用itertuples的时候可以直接用i.Index拿索引,i.column_1拿列值,但转成字典后不知道怎么实现同样的操作。

原代码示例:

import pandas as pd
from IPython.display import display

df = pd.DataFrame(data={'column_1': [1,2,3,4,5], 'column_2':[5,10,15,20,25], 'column_3':[3,6,9,12,15], 'column_4':[8,7,6,5,4]})
display(df)

# 原来用itertuples的代码
for i in df.itertuples():
  if i.Index % 2 == 0:
    print('column_1 value using itertuples',i.column_1)
  else:
    print('skip this row using itertuples')

# 尝试转字典后的错误代码
df_dict = df.to_dict('records')
for row in df_dict:
  for index, (key,value) in enumerate(row.items()):
    if index % 2 == 0:
      print('column_1 value',row['column_1']) ### this does not work
    else:
      print('skip this row')

解决方案

你的错误在于嵌套遍历了行内的键值对——df.to_dict('records')返回的是每行对应一个字典的列表,不需要再循环行里的items()。另外默认转字典时原索引不会包含在字典里,分两种场景处理:


场景1:原DataFrame用默认连续整数索引

如果索引是0、1、2...这类连续整数,直接用enumerate遍历字典列表就能拿到和原Index一致的索引值:

df_dict = df.to_dict('records')
# enumerate第一个参数是行的索引位置,第二个是行字典
for idx, row in enumerate(df_dict):
    if idx % 2 == 0:
        print('column_1 value using dict', row['column_1'])
    else:
        print('skip this row using dict')

运行后输出和itertuples版本完全一致,且遍历速度更快。


场景2:原DataFrame用自定义非连续索引

如果用了自定义索引(比如字符串、非连续整数),先把索引转成普通列再转字典:

# 将原索引转为名为'index'的列,再生成字典列表
df_dict_with_index = df.reset_index().to_dict('records')
for row in df_dict_with_index:
    # 原索引存在row['index']中,列值直接通过键名获取
    if row['index'] % 2 == 0:
        print('column_1 value with custom index', row['column_1'])
    else:
        print('skip this row with custom index')

这样就能获取原DataFrame的真实索引值,而非遍历的位置序号。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:12:54