【发布时间】:2021-07-20 16:38:42
【问题描述】:
我用 python 编写了一个预处理脚本,有助于巩固信心。以下是我的脚本:
import pandas as pd
import numpy as np
from pathlib import Path
import glob as glob
inp_dir = Path(r'C:/Users/jtharian/Desktop/bbc/')
for file in inp_dir.glob('*.csv'):
df = pd.read_csv(file, sep=',', quotechar='|',error_bad_lines=False)
df['confidence'] = df['confidence'].replace(np.nan, 0.01)
df.to_csv(file,index=False)
错误:
Traceback (most recent call last):
File "C:\Users\jtharian\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'confidence'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<ipython-input-1-0cbf17caf540>", line 11, in <module>
df['confidence'] = df['confidence'].replace(np.nan, 0.01)
File "C:\Users\jtharian\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py", line 3024, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Users\jtharian\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: 'confidence'
我不明白我收到此错误是因为我的目录中的一个文件没有“置信度”列。但是如何找到该文件或打印文件名?
【问题讨论】:
-
当你读取df中的csv时,检查列confidence是否存在!!比如
if 'confidence' in df.columns,你有file变量,打印出来。 -
将
print(file)放在循环的开头。问题出在错误之前打印的文件名中。