CSV到DF的字节以绕过UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的起始字节?

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

我有一个csv,以前我没有任何问题地将其读取到数据帧,但是现在却出现以下错误:UnicodeDecodeError:“ utf-8”编解码器无法解码位置0的字节0xff:无效的起始字节

df = pd.read_csv(r'\\blah\blah2\csv.csv')

我尝试过:

df = pd.read_csv(r'\\blah\blah2\csv.csv', encoding = 'utf-8-sig')

但是这给了我这个错误:UnicodeDecodeError:'utf-8-sig'编解码器无法解码位置10423中的字节0xff:无效的起始字节

因此,我尝试了'utf-16',但这给了我这个错误:UnicodeError:UTF-16流不是以BOM表开头的>>

然后我尝试了此:

with open(r'\\blah\blah2\csv.csv', 'rb') as f:
contents = f.read()

并且有效,但是我需要将csv作为数据框,所以我尝试了:

new_df = pd.DataFrame.to_string(contents)

但我收到此错误:AttributeError:'bytes'对象没有属性'columns'

有人能帮我得到我的数据帧吗?

谢谢。

更新:

此问题已解决。它将csv读入数据帧而没有unicode错误。

df = pd.read_csv(r'\\blah\blah2\csv.csv', encoding='latin1')
    

我有一个csv,我以前已经读它到数据帧了,没有问题,但是现在给我以下错误:UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的开始...] >

python pandas csv unicode byte
2个回答
0
投票

尝试使用下面的代码找到正确的编码:

# import the chardet library
import chardet 

# use the detect method to find the encoding
# 'rb' means read in the file as binary
with open(your_file, 'rb') as file:
    print(chardet.detect(file.read()))

0
投票

此问题已解决。它将csv读入数据帧而没有unicode错误。

© www.soinside.com 2019 - 2024. All rights reserved.