Python pandas excel UnicodeDecodeError:'ascii'编解码器无法解码位置11的字节0xe2

时间:2017-12-07 15:46:07

标签: python dataframe encoding utf-8

在网络抓取电子商务网站后,我已将所有数据保存到pandas数据框中。好吧,当我试图将我的pandas数据帧保存到excel文件时,我收到以下错误:

Traceback (most recent call last):

File "<ipython-input-7-3dafdf6b87bd>", line 2, in <module>
  sheet_name='Dolci', encoding='iso-8859-1')

File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\frame.py", line 
  1466, in to_excel
     excel_writer.save()

File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\io\excel.py", line 
  1502, in save
     return self.book.close()

File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\workbook.py", 
  line 299, in close
     self._store_workbook()

File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\workbook.py", 
  line 607, in _store_workbook
     xml_files = packager._create_package()

File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\packager.py", 
  line 139, in _create_package
     self._write_shared_strings_file()

File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\packager.py", 
  line 286, in _write_shared_strings_file
     sst._assemble_xml_file()

File "C:\ProgramData\Anaconda2\lib\site-
  packages\xlsxwriter\sharedstrings.py", line 53, in _assemble_xml_file
     self._write_sst_strings()

File "C:\ProgramData\Anaconda2\lib\site-
  packages\xlsxwriter\sharedstrings.py", line 83, in _write_sst_strings
     self._write_si(string)

File "C:\ProgramData\Anaconda2\lib\site-
  packages\xlsxwriter\sharedstrings.py", line 110, in _write_si
     self._xml_si_element(string, attributes)

File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\xmlwriter.py", 
  line 122, in _xml_si_element
     self.fh.write("""<si><t%s>%s</t></si>""" % (attr, string))

File "C:\ProgramData\Anaconda2\lib\codecs.py", line 706, in write
     return self.writer.write(data)

File "C:\ProgramData\Anaconda2\lib\codecs.py", line 369, in write
     data, consumed = self.encode(object, self.errors)


UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 11: 
ordinal not in range(128)

我使用的代码是:

df.to_excel('my_file.xlsx',sheet_name='Dolci', encoding='iso-8859-1')

但它不起作用,我甚至尝试过:

df.to_excel('my_file.xlsx',sheet_name='Dolci', encoding='utf-8')

但它仍然给我错误。 有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:9)

似乎您在ExcelWriter中使用xlsxwriter引擎。 请尝试使用openpyxl。

writer = pd.ExcelWriter('file_name.xlsx', engine='openpyxl')
df.to_excel(writer)
writer.save()

答案 1 :(得分:3)

to_excel方法有一个基本参数,请尝试

df.to_excel('filename.xlsx', engine='openpyxl')

它对我有用。

答案 2 :(得分:0)

添加@Vadym的响应,您可能必须关闭编写器才能创建文件。

*[0..9]

&#34;取决于所用引擎的行为&#34;

请参阅: https://github.com/pandas-dev/pandas/issues/9145 这应该是一个评论,但我没有代表...