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

Python数据保存至CSV后跨Notebook读取报错的解决方法

问题:保存CSV后用Pandas读取出现KeyError:0的解决办法

问题场景

为避免重复运行Python代码,将Fobs、Sobs、Hobs三个列表保存为CSV文件,保存代码如下:

import csv
with open(path + '/data_robs.csv', 'w', newline='') as csvfile:
     fieldnames = ['Fobs', 'Sobs', 'Hobs']
     writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
     writer.writeheader()
     for i in range(len(Fobs)):
         writer.writerow({'Fobs': Fobs[i], 'Sobs': Sobs[i], 'Hobs': Hobs[i]})

在另一个Notebook中读取文件:

import pandas as pd
data_robs = pd.read_csv(path + str("\") + str("data_robs.csv"))

执行data_robs[0]访问数据时触发KeyError错误,错误信息如下:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py:3621, in Index.get_loc(self, key, method, tolerance)
   3620 try:
-> 3621     return self._engine.get_loc(casted_key)
   3622 except KeyError as err:

File ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx:136, in pandas._libs.index.IndexEngine.get_loc()

File ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx:163, in pandas._libs.index.IndexEngine.get_loc()

File pandas\_libs\hashtable_class_helper.pxi:5198, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas\_libs\hashtable_class_helper.pxi:5206, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 data_robs[0]

File ~\anaconda3\lib\site-packages\pandas\core\frame.py:3505, in DataFrame.__getitem__(self, key)
   3503 if self.columns.nlevels > 1:
   3504     return self._getitem_multilevel(key)
-> 3505 indexer = self.columns.get_loc(key)
   3506 if is_integer(indexer):
   3507     indexer = [indexer]

File ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py:3623, in Index.get_loc(self, key, method, tolerance)
   3621     return self._engine.get_loc(casted_key)
   3622 except KeyError as err:
-> 3623     raise KeyError(key) from err
   3624 except TypeError:
   3625     # If we have a listlike key, _check_indexing_error will raise
   3626     #  InvalidIndexError. Otherwise we fall through and re-raise
   3627     #  the TypeError.
   3628     self._check_indexing_error(key)

KeyError: 0

问题原因

这不是保存方式的问题,而是对Pandas DataFrame的访问逻辑理解有误:

  • data_robs是Pandas DataFrame对象,data_robs[key]的语法用于按列名检索列,而非按行索引访问行。你的CSV列名为Fobs、Sobs、Hobs,不存在名为0的列,因此触发KeyError。

解决方法

1. 正确访问行数据

如果要按位置访问第N行(从0开始计数),使用iloc属性:

# 获取第一行数据
first_row = data_robs.iloc[0]

如果要按索引值访问行(默认索引是0开始的整数),也可以用loc:

first_row = data_robs.loc[0]

2. 访问列数据

如果要获取整列数据,直接用列名:

# 获取Fobs列的所有数据
fobs_column = data_robs['Fobs']

3. 优化保存代码(可选)

用Pandas直接保存数据会更简洁,避免手动循环写入,减少出错概率:

import pandas as pd
# 将三个列表转为DataFrame
df = pd.DataFrame({'Fobs': Fobs, 'Sobs': Sobs, 'Hobs': Hobs})
# 保存为CSV(index=False避免写入默认索引列)
df.to_csv(path + '/data_robs.csv', index=False)

读取代码也可以简化(用f-string避免路径转义问题):

data_robs = pd.read_csv(f"{path}/data_robs.csv")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:55:44