python - 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'
,但是在连接它们之前我不知道该怎么做。
无论如何,任何信息或建议将不胜感激!我导入的一些模块是用于代码的前面部分的,我只是无法让这个特定部分工作。
解决方案
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')
推荐阅读
- javascript - 如何在打字稿中扩展工厂方法
- linux - error.log 中 apache2 的问题 apache 2 无法启动?
- spring-boot - Hibernate:如何将自动生成的外键列名从小写更改为大写
- angular - 在 Angular 10 ASP.NET Core 3.1 SPA 应用程序中处理浏览器重新加载的正确方法是什么?
- sql - 如何在 BigQuery 中使用 LAG 和 OVER 计算每周移动平均值的百分比变化?
- sql - proc sql:一步计算基于不同条件的多个汇总统计信息
- ios - 在特定时间段后停止本地通知
- python - 如何提高CNN的预测准确率
- elixir - 如何同时插入 2 个对象但相差 1 秒?
- javascript - 为什么当在另一个对象中传播对象时,我在浏览器中得到的输出与在节点中不同?