【问题标题】:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte, while reading csv file in pandasUnicodeDecodeError:“utf-8”编解码器无法解码位置 1 的字节 0x8b:无效的起始字节,同时读取熊猫中的 csv 文件
【发布时间】:2017-11-23 09:34:08
【问题描述】:

我知道已经有人问过类似的问题,我已经看过所有这些问题并尝试过,但帮助不大。我正在使用 OSX 10.11 El Capitan,python3.6.,虚拟环境,也尝试过没有它。我正在使用 jupyter notebook 和 spyder3。

我是 python 新手,但了解基本的 ML 并关注一个帖子来学习如何解决 Kaggle 挑战:Link to BlogLink to Data Set

.我卡在前几行代码上 `

import pandas as pd

destinations = pd.read_csv("destinations.csv")
test = pd.read_csv("test.csv")
train = pd.read_csv("train.csv")

它给了我错误

UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-19-a928a98eb1ff> in <module>()
      1 import pandas as pd
----> 2 df = pd.read_csv('destinations.csv', compression='infer',date_parser=True, usecols=([0,1,3]))
      3 df.head()

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654 
--> 655         return _read(filepath_or_buffer, kwds)
    656 
    657     parser_f.__name__ = name

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    403 
    404     # Create the parser.
--> 405     parser = TextFileReader(filepath_or_buffer, **kwds)
    406 
    407     if chunksize or iterator:

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, f, engine, **kwds)
    762             self.options['has_index_names'] = kwds['has_index_names']
    763 
--> 764         self._make_engine(self.engine)
    765 
    766     def close(self):

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in _make_engine(self, engine)
    983     def _make_engine(self, engine='c'):
    984         if engine == 'c':
--> 985             self._engine = CParserWrapper(self.f, **self.options)
    986         else:
    987             if engine == 'python':

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, src, **kwds)
   1603         kwds['allow_leading_cols'] = self.index_col is not False
   1604 
-> 1605         self._reader = parsers.TextReader(src, **kwds)
   1606 
   1607         # XXX

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.__cinit__ (pandas/_libs/parsers.c:6175)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._get_header (pandas/_libs/parsers.c:9691)()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

关于 stakoverflow 的一些答案表明这是因为它是 gzip 压缩的,但是 Chrome 下载了 .csv 文件并且 .csv.gz 无处可见,并且返回了文件未找到错误。

然后我在某处阅读以使用encoding='latin1',但这样做后我收到解析器错误:

---------------------------------------------------------------------------
ParserError                               Traceback (most recent call last)
<ipython-input-21-f9c451f864a2> in <module>()
      1 import pandas as pd
      2 
----> 3 destinations = pd.read_csv("destinations.csv",encoding='latin1')
      4 test = pd.read_csv("test.csv")
      5 train = pd.read_csv("train.csv")

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654 
--> 655         return _read(filepath_or_buffer, kwds)
    656 
    657     parser_f.__name__ = name

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    409 
    410     try:
--> 411         data = parser.read(nrows)
    412     finally:
    413         parser.close()

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in read(self, nrows)
   1003                 raise ValueError('skipfooter not supported for iteration')
   1004 
-> 1005         ret = self._engine.read(nrows)
   1006 
   1007         if self.options.get('as_recarray'):

/usr/local/lib/python3.6/site-packages/pandas/io/parsers.py in read(self, nrows)
   1746     def read(self, nrows=None):
   1747         try:
-> 1748             data = self._reader.read(nrows)
   1749         except StopIteration:
   1750             if self._first_chunk:

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read (pandas/_libs/parsers.c:10862)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory (pandas/_libs/parsers.c:11138)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows (pandas/_libs/parsers.c:11884)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows (pandas/_libs/parsers.c:11755)()

pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error (pandas/_libs/parsers.c:28765)()

ParserError: Error tokenizing data. C error: Expected 2 fields in line 11, saw 3

我花了几个小时来调试这个,试图在 Atom 上打开 csv 文件(没有其他应用程序可以打开它),在线网络应用程序(一些崩溃)但没有帮助。我尝试过使用其他人的内核谁解决了问题,但无济于事。

【问题讨论】:

  • 分隔符是什么?
  • 我不知道。我对所有这些都是新手。我刚刚下载了帖子中给出的数据集并尝试执行这些行,但出现错误。我不知道如何知道分隔符,我已经提到了顶部的链接也许你可以找到。谢谢

标签: python python-3.x csv pandas kaggle


【解决方案1】:

在读取 csv 文件时尝试包含此编码

pd.read_csv('csv_file', encoding='ISO-8859–1')

【讨论】:

    【解决方案2】:

    它仍然很可能是压缩后的数据。 gzip的幻数是0x1f 0x8b,和你得到的UnicodeDecodeError一致。

    您可以尝试即时解压缩数据:

    with open('destinations.csv', 'rb') as fd:
        gzip_fd = gzip.GzipFile(fileobj=fd)
        destinations = pd.read_csv(gzip_fd)
    

    【讨论】:

    • 谢谢!它起作用了。但我想知道为什么它发生在我身上的一件事,其他这样做的人没有得到错误。喜欢看一个提交:kaggle.com/benjaminabel/pandas-version-of-most-popular-hotels
    • 我假设提交只适用于已经解压缩的输入文件。
    • 但我的文件显示的 .csv 扩展名与 chrome 下载的相同。那么它怎么可能被拉上拉链呢?不应该是 .csv.gz 吗?
    • 看我不知道你或其他人的浏览器的细节。这里重要的是,如果文件被 gzip 压缩,您需要在将其提供给 pandas 之前对其进行解压缩。
    【解决方案3】:

    你可以尝试使用编解码器

    import codecs
    with codecs.open("destinations.csv", "r",encoding='utf-8', errors='ignore') as file_dat:
         destinations = pd.read_csv(file_data))
    

    【讨论】:

    • 我试过但得到错误:ParserError: 错误标记数据。 C 错误:预计第 11 行中有 2 个字段,看到 3
    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2021-12-01
    • 2016-05-13
    • 2020-02-06
    • 2021-10-22
    相关资源
    最近更新 更多