CSV到字节到DF绕过UnicodeDecodeError:“utf8”编解码器无法解码位置0中的字节0xff:起始字节无效?

2024-04-25 20:54:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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')

Tags: csv数据dfread字节错误编解码器解码
2条回答

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

# 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()))

但是,不能保证找到编码,因为上下文可能包含不同的编码或不同的语言,但是,如果它仅由1个代码编码,则可以看到这一点

pip(3) install chardet

如果你没有安装

编辑1: 下面是找到正确编码的另一种方法。如果上述问题没有解决,这可能会有所帮助:

from encodings.aliases import aliases
alias_values = set(aliases.values())

for value in alias_values:
    try:
        df = pd.read_csv(your_file, encoding=value) # or pd.read_excel
        print(value)
    except:
        continue

这把它修好了。它将csv读取到一个数据帧中,没有unicode错误

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

相关问题 更多 >

    热门问题