DataFrame行子集筛选后迭代报错KeyError:10问题排查
问题分析与解决
你遇到的KeyError:10并非筛选子集的代码有误,而是迭代子集DataFrame的方式错误:
- 用
loc筛选生成的df_selected_brands会保留原DataFrame的索引,这些索引大概率不是连续的整数序列。 - 你的循环用
range(len(df_selected_brands))生成0到N-1的序号,然后通过df_selected_brands['id'][item]访问数据——这是按索引值取数,而非按位置取数。如果原DataFrame的索引中不存在10这个值,就会触发KeyError。 - 原DataFrame迭代正常只是因为它的索引刚好是连续的,和
range()生成的序号巧合匹配,这不是通用的正确写法。
解决方法(任选其一)
- 用
iloc按位置访问(推荐,无需修改索引)
for item in range(len(df_selected_brands)): product_id = df_selected_brands['id'].iloc[item] print(product_id)
- 直接迭代列的数值(最简洁)
for product_id in df_selected_brands['id'].values: print(product_id)
- 重置子集的索引(适合后续需要用索引操作的场景)
先重置索引再执行循环:
df_selected_brands = df_all_products.loc[df_all_products['brands'].isin(lst_of_brands)].reset_index(drop=True) # 原循环代码可正常运行 for item in range(len(df_selected_brands)): product_id = df_selected_brands['id'][item] print(product_id)
内容的提问来源于stack exchange,提问作者Ron Kieftenbeld
相关产品推荐
相关产品推荐

