我正在运行一个处理30000个类似文件的程序。他们中的随机数正在停止并产生这个错误。。。
File "C:\Importer\src\dfman\importer.py", line 26, in import_chr
data = pd.read_csv(filepath, names=fields)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 400, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 205, in _read
return parser.read()
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 608, in read
ret = self._engine.read(nrows)
File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 1028, in read
data = self._reader.read(nrows)
File "parser.pyx", line 706, in pandas.parser.TextReader.read (pandas\parser.c:6745)
File "parser.pyx", line 728, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:6964)
File "parser.pyx", line 804, in pandas.parser.TextReader._read_rows (pandas\parser.c:7780)
File "parser.pyx", line 890, in pandas.parser.TextReader._convert_column_data (pandas\parser.c:8793)
File "parser.pyx", line 950, in pandas.parser.TextReader._convert_tokens (pandas\parser.c:9484)
File "parser.pyx", line 1026, in pandas.parser.TextReader._convert_with_dtype (pandas\parser.c:10642)
File "parser.pyx", line 1046, in pandas.parser.TextReader._string_convert (pandas\parser.c:10853)
File "parser.pyx", line 1278, in pandas.parser._string_box_utf8 (pandas\parser.c:15657)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xda in position 6: invalid continuation byte
这些文件的来源/创建都来自同一个地方。要继续导入,更正此错误的最佳方法是什么?
Pandas允许指定编码,但不允许忽略错误而不自动替换有问题的字节。因此,没有“一刀切”的方法,而是根据实际的用例采用不同的方法。
您知道编码,并且文件中没有编码错误。 很好:您只需指定编码:
你不想被编码问题所困扰,只想加载那个该死的文件,不管某些文本字段是否包含垃圾。好的,您只需使用
Latin1
编码,因为它接受任何可能的字节作为输入(并将其转换为相同代码的unicode字符):您知道,大多数文件是用特定的编码编写的,但它也包含编码错误。一个真实的例子是一个用非UTF8编辑器编辑的UTF8文件,它包含一些不同编码的行。Pandas没有提供特殊的错误处理,但是Python
open
函数有(假设Python3),并且read_csv
接受类似文件的对象。这里使用的典型错误参数是'ignore'
,它只抑制有问题的字节,或者(最好)用Python的反斜杠转义序列替换有问题的字节:read_csv
使用encoding
选项处理不同格式的文件。我通常用read_csv('file', encoding = "ISO-8859-1")
,或者encoding = "utf-8"
来阅读,通常用utf-8
来阅读to_csv
。您还可以使用几个
alias
选项中的一个,例如'latin'
,而不是'ISO-8859-1'
(请参见python docs,也可以查看您可能遇到的许多其他编码)。见relevant Pandas documentation, python docs examples on csv files,还有很多相关的问题。一个好的背景资源是What every developer should know about unicode and character sets。
要检测编码(假设文件包含非ascii字符),可以使用
enca
(请参见man page)或file -i
(linux)或file -I
(osx)(请参见man page)。最简单的解决方案:
替代溶液:
然后,您可以像往常一样读取文件:
其他不同的编码类型有:
相关问题 更多 >
编程相关推荐