问题描述
如果这看起来像是重复的帖子,我深表歉意,但是我已经花了2个小时在stackoverflow上进行搜索,但还没有找到解决方案。
我正在将csv文件加载到pandas中,并在数据框中使用一些列。 问题在于,其中一列的名称中带有度符号°。
如果我手动从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 / 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
1楼
这段代码对我有用:
df = pd.read_csv('your.csv',encoding ="latin1")
2楼
你有几次错别字。
您正在将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'})