首页 > 解决方案 > CSV 到字节到 DF 以绕过 UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 的字节 0xff:无效的起始字节?

问题描述

我有一个 csv,我之前已经毫无问题地读取到数据帧,但现在给了我以下错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

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' codec can't decode byte 0xff in position 10423: invalid start byte

然后我尝试了“utf-16”,但这给了我这个错误:UnicodeError:UTF-16 stream does not start with BOM

然后我尝试了这个:

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

这行得通,但我需要那个 csv 作为数据框,所以我尝试了:

new_df = pd.DataFrame.to_string(contents)

但我收到了这个错误:AttributeError: 'bytes' object has no attribute 'columns'

有人可以帮我获取我的数据框吗?

谢谢你。

更新:

这解决了它。它将 csv 读入没有 unicode 错误的数据帧。

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

标签: pythonpandascsvunicodebyte

解决方案


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

# 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

如果你没有安装它

EDIT1:以下是找到正确编码的另一种方法。如果以上没有,这可能会有所帮助:

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

推荐阅读