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

使用Pandas dropna后出现KeyError:69,问题原因是什么?

问题原因及解决方法

原因分析

不是dropna的使用错误,而是索引不连续导致的KeyError。

  • dropna(inplace=True)只会删除包含空值的行,但不会自动重置DataFrame的索引。如果原数据中索引为69的行被删掉了,the_pH作为Series会保留原有的索引序列,此时索引是不连续的。
  • 你用range(len(the_pH))生成连续的整数序号(0,1,2,...),但当i=69时,the_pH的索引里已经没有这个值,自然触发KeyError。

解决方法

给你三种实用的处理方式:

1. 重置索引

在dropna之后添加重置索引的代码,让索引变回连续序列:

the_data.dropna(inplace=True)
the_data.reset_index(drop=True, inplace=True)  # 重置索引,drop=True丢弃原索引列

这样the_pH的索引就会变成连续的0,1,2,...,再用range(len(the_pH))遍历就不会出错。

2. 直接遍历Series的值

不需要通过索引访问,直接遍历the_pH的元素,这是Pandas里最推荐的遍历方式:

for ph_value in the_pH:
    print(ph_value)

3. 用enumerate同时获取序号和值

如果需要同时拿到连续序号和对应的pH值,可以用enumerate:

for idx, ph_value in enumerate(the_pH):
    print(idx)
    print(ph_value)

这里的idx是连续的序号,和原Series的索引无关,完全避免索引不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:05:38