欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

搞定pandas读取文件时常见的UnicodeDecodeError问题的实用方法

最编程 2024-02-03 21:04:03
...

如果我们遇到UnicodeDecodeError,一般而言是因为编码错误。所以尝试其他编码是个不错的选择。

但一一尝试速度较慢,我们不妨使用chardet库和pandas读文件时encoding_errors='ignore'共同解决问题。

chardet库可以帮我们检测可能的编码。

import pandas as pd
import numpy as np
import chardet

# look at the first ten thousand bytes to guess the character encoding
with open("ks-projects-201801.csv", 'rb') as rawdata:
    result = chardet.detect(rawdata.read(10000))

# check what the character encoding might be
print(result)

结果为

{'encoding': 'Windows-1252', 'confidence': 0.73, 'language': ''}

可以看出,编码为Windows-1252。

但当我们非常高兴地读文件时:

kickstarter_2016 = pd.read_csv("ks-projects-201801.csv", encoding='Windows-1252')
# look at the first few lines
kickstarter_2016.head()

高置信度的Windows-1252编码好像出了问题:

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12864/300630660.py in <module>
      1 # read in the file with the encoding detected by chardet
      2 # kickstarter_2016 = pd.read_csv("ks-projects-201801.csv", encoding='Windows-1252',encoding_errors='ignore')
----> 3 kickstarter_2016 = pd.read_csv("ks-projects-201801.csv", encoding='Windows-1252')
      4 # look at the first few lines
      5 kickstarter_2016.head()

所以,我们继续改代码,把为数较少的错误ignore掉:

kickstarter_2016 = pd.read_csv("ks-projects-201801.csv", encoding='Windows-1252',encoding_errors='ignore')
# look at the first few lines
kickstarter_2016.head()

结果为

 看着还不错(doge)

推荐阅读