由于unicode解码错误,无法在pandas中打开csv文件

问题描述 投票:2回答:3

我将pandas数据帧保存为csv使用

df_to_save.to_csv(save_file_path)

但是当我用它读回来的时候

df_temp = pd.read_csv(file_path)

我收到一条错误消息说

UnicodeDecodeError:'utf-8'编解码器无法解码158位的字节0xbf:无效的起始字节

我已经尝试通过打开csv文件强制编码将其读取为utf-8

df_temp = pd.read_csv(file_path, index_col=False, encoding="utf-8",sep=',') 

真的卡住了,有人可以帮忙吗?

非常感谢

python python-3.x pandas
3个回答
4
投票

更改分类数据的编码:

def my_func(df):
    for col in df.columns:
        df[col] = df[col].str.decode('iso-8859-1').str.encode('utf-8')

此功能将根据您的分类数据的编码进行就地更改。


3
投票

该字符未以UTF-8编码。

您可以使用(docs)重现它:

b'\xbf'.decode("utf-8", "strict")
Traceback (most recent call last):

  File "<ipython-input-7-4db5a43b4577>", line 1, in <module>
    b'\xbf'.decode("utf-8", "strict")

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

您可以尝试不同的编码,这将解决此角​​色的问题:

b'\xbf'.decode("ISO-8859-1", "strict")
Out: '¿'

所以你的read_csv会改为:

df_temp = pd.read_csv(file_path, index_col=False, encoding="ISO-8859-1") 

0
投票

或者避免编码问题使用EXCEL(也返回DataFrames)

writer = pd.ExcelWriter('train_numeric.xlsx')
newTRAIN.to_excel(writer,'Sheet1')

然后

newTEST_excel = pd.read_excel('train_numeric.xlsx')
newTEST_excel.head(2)
© www.soinside.com 2019 - 2024. All rights reserved.