首页 > 解决方案 > UnicodeDecodeError - 从一个目录连接多个 csv 的问题

问题描述

我正在尝试(垂直)连接一堆 csv 文件(大约 50 个),它们都在同一个文件夹中,保存到我的笔记本电脑中,并且它们都有相同的标题。

但是,当我尝试执行此操作时,我收到以下错误消息:

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

我不太确定是什么原因造成的。可能是 csv 文件中有一些奇怪的字符吗?例如,列中的值之一是"rÊ¢ªºbþ0.32639"。我的数据集中有一些像这样的异常现象,我相信是由于测量仪器出现故障。由于海量数据和大量 csv 文件,遍历并手动删除这些测量值太费时,而且不是一种选择。

到目前为止我的代码:

import pandas as pd    
import numpy as np    
import os    
import glob    
from datetime import datetime

os.chdir("PATH")    

# Use glob to match the pattern csv    
extension_EC1 = 'csv'    
all_filenames_EC1 = [i for i in glob.glob('*.{}'.format(extension_EC1))]

# Combine all files in the list     
combined_EC1_csv = pd.concat([pd.read_csv(f) for f in all_filenames_EC1])

# Export to csv    
combined_EC1_csv.to_csv("combined_csv_EC1", index=False, encoding='utf-8-sig')

错误指向脚本中的连接行。我想知道在此之前我可能需要将它们编码为 utf8 吗?并忽略错误?我在这里查看了许多线程,它们在读取 csv 时似乎都进行了编码。我只是无法得到任何工作,因为我发现没有事先列出目录中所有 csv 文件的列表。另外,我发现一些线程说要使用encoding='cp1252',但是在连接它们之前我不知道该怎么做。

无论如何,任何信息或建议将不胜感激!我导入的一些模块是用于代码的前面部分的,我只是无法让这个特定部分工作。

标签: pythonpython-3.xpandascsv

解决方案


pandas的read_csv方法有一个参数叫做encoding。您可以在参数中传递您选择的编码并读取 csv

例如,如果您希望将cp1252编码应用于 csv 文件,您可以尝试此代码

import pandas as pd    
import numpy as np    
import os    
import glob    
from datetime import datetime

os.chdir("PATH")    

# Use glob to match the pattern csv    
extension_EC1 = 'csv'    
all_filenames_EC1 = [i for i in glob.glob('*.{}'.format(extension_EC1))]

# Combine all files in the list in a single df, along the columns
#Change Axis value to 0 if the number of columns in the csv files are
# not the same across all the files.

combined_EC1_csv = pd.concat([pd.read_csv(f,encoding='cp1252') for f in all_filenames_EC1],axis=1)

# Export to csv    
combined_EC1_csv.to_csv("combined_csv_EC1", index=False, encoding='utf-8-sig')

推荐阅读