python - 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')
解决方案
尝试使用以下代码找到正确的编码:
# 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
推荐阅读
- ruby-on-rails - 找不到 gem “在任何来源中都找不到 aws-sigv4-1.0.0”
- c# - 找不到编译动态表达式所需的一种或多种类型。您是否缺少参考?
- javascript - React v16.4.1 - 未捕获的类型错误:导入 React 类时无法读取未定义的属性“对象”
- ios - 如何从使用结构创建的数组中追加项目?
- wpf - 访问在其绑定之外的 ItemTemplate 内部调用的属性
- json - 如何为 REST 响应中的同一字段解析 jsonObject 和 JsonArray
- acumatica - 在 APInvoice DAC 上使用 APRegisterExt
- java - 在 Ubuntu 中连接到 VPN
- android - 发现依赖默认编码:new java.io.FileWriter(File, boolean)
- python - 将数组存储为 Pandas 列中的值