我很抱歉,如果这看起来像一个重复的帖子,但我已经花了2个小时搜索堆栈溢出,但还没有找到解决方案。
我将一个csv文件加载到熊猫中,并使用一些列作为我的数据格式。问题是其中一个列的名称°中有一个度符号。
如果我手动删除°从csv,我可以加载到熊猫没有问题。然而,我将有数百个这些文件通过,所以手动删除听起来不好玩。
这是我收到的错误:
"UnicodeDecodeError:'utf-8‘编解码器无法解码位置6中的字节0xb0 :无效的开始字节“
# coding: utf-8
import googlemaps
import folium
import pandas as pd
import re
df = pd.read_csv('{}{}{}'.format(path, filename, '.csv', encoding='utf-8',errors="ignore"))
.rename(columns={'GPS_x[°]': 'lng', 'GPS_y[°]': 'lat',
'ELEVATION_FT[Ft]': 'ele_ft'})我试过将其编码为latin1 1/iso-8859-1,但没有成功。我使用Pycharm作为我的IDE,默认的文件编码是UTF-8。
我还尝试在notepad++中打开csv文件并将其编码为UTP-8并保存一个新文件,但仍然会得到相同的错误。我不知道该怎么办
编辑1:回溯(最近一次调用):
File "myfile.py", line 18, in <module>
df = pd.read_csv('{}{}{}'.format(path, filename, '.csv', errors="ignore")).rename(columns={'GPS_x[°]': 'lng', 'GPS_y[°]': 'lat', 'ELEVATION_FT[Ft]': 'ele_ft'})
File "C:\Users\name\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 645, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Users\name\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 388, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "C:\Users\name\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 729, in __init__
self._make_engine(self.engine)
File "C:\Users\name\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 922, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "C:\Users\name\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1389, in __init__
self._reader = _parser.TextReader(src, **kwds)
File "pandas\parser.pyx", line 535, in pandas.parser.TextReader.__cinit__ (pandas\parser.c:6077)
File "pandas\parser.pyx", line 738, in pandas.parser.TextReader._get_header (pandas\parser.c:9215)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 11: invalid start byte发布于 2017-02-10 17:22:26
你有几个排字。您将encoding=传递给format(),而不是read_csv(),后者随后被忽略。
errors在这里也是错误的,因为read_csv不支持它。
当您的编码被notepad++报告为ANSI时,您应该使用mbcs作为编解码器。ANSI是指您所在区域的8位字符集,如果您是为西欧配置的,就像windows-1252。Python中的mbcs使用相同的区域设置来解码/编码。
df = pd.read_csv('{}{}{}'.format(path, filename, '.csv'), encoding='mbcs').rename(columns={'GPS_x[°]': 'lng', 'GPS_y[°]': 'lat', 'ELEVATION_FT[Ft]': 'ele_ft'})为了使阅读更容易,这可能有助于您更快地发现问题,您应该这样做:
fq_filename = '{}{}{}'.format(path, filename, '.csv')
df = pd.read_csv(fq_filename, encoding='mbcs')
df = df.rename(columns={'GPS_x[°]': 'lng', 'GPS_y[°]': 'lat', 'ELEVATION_FT[Ft]': 'ele_ft'})发布于 2017-02-10 01:42:28
这段代码适用于我:
df = pd.read_csv('your.csv',encoding ="latin1")https://stackoverflow.com/questions/42149829
复制相似问题