本文主要是介绍pandas读文件时中UnicodeDecodeError常用解决方案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如果我们遇到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 chardet2 # 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 lines5 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)
这篇关于pandas读文件时中UnicodeDecodeError常用解决方案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!