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

使用Python DataFrame副本时出现KeyError:9错误求助

解决DataFrame删除行后遍历触发KeyError的问题

问题原因

你猜的没错,问题根源就是删除行后的索引不连续:

  • jobsDFCopy.dropna()删除含NaN的行后,DataFrame保留了原索引编号(比如原行9被删除后,索引序列中就没有9了)
  • 但你用range(jobsDFCopy.shape[0])生成的是连续数字序列(0,1,2,...,n-1),当循环到i=9时,去DataFrame中查找索引9就会触发KeyError
  • 原DataFramedf未删除过行,索引连续,所以findCompCertAnn能正常运行

修复方案

方案1:重置索引(适配原函数逻辑)

在删除行后调用reset_index(drop=True),让索引重新变为连续的0到n-1:

jobsDFCopy = df.copy()
jobsDFCopy.dropna(subset=['Certified Jobs'], inplace=True)
jobsDFCopy.reset_index(drop=True, inplace=True)  # 新增该行重置索引

修改后原findJobsCertAnn函数即可正常执行。

方案2:迭代行(更规范的pandas写法)

放弃通过索引值遍历,改用iterrows()直接迭代每一行,彻底避开索引问题:

def findJobsCertAnn(thresholdYear):
    jobCount = 0
    for _, row in jobsDFCopy.iterrows():
        if (thresholdYear - 1) < row['Years Since Approval'] <= thresholdYear:
            jobCount += row['Certified Jobs']
    return jobCount

方案3:矢量化操作(最高效)

利用pandas的布尔索引和内置求和方法,完全替代循环,大数据量下效率提升明显:

def findJobsCertAnn(thresholdYear):
    # 生成布尔掩码筛选符合条件的行
    mask = (jobsDFCopy['Years Since Approval'] > (thresholdYear - 1)) & \
           (jobsDFCopy['Years Since Approval'] <= thresholdYear)
    # 对筛选后的'Certified Jobs'列求和
    return jobsDFCopy.loc[mask, 'Certified Jobs'].sum()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:53:30