gpt4 book ai didi

python - Pandas 读取多个文件时读取 CSV 错误

转载 作者:行者123 更新时间:2023-12-05 04:23:46 28 4
gpt4 key购买 nike

我有多个 csv 文件,命名为 2C-BEB-29-2009-01-18.csv,2C-BEB-29-2010-02-18.csv,2C-BEB-29-2010-03-28 .csv、2C-ISI-12-2010-01-01.csv 等。

  • 2C- Part 在所有 csv 文件中都是默认的。

  • BEB表示录音设备的名称

  • 29代表用户ID

  • 2009-01-18代表录制日期。

我有大约 150 个不同的 ID 和他们在不同设备上的录音。我想将我为所有用户 ID 的单个用户 ID 所做的以下方法自动化

当我为单个用户使用以下代码时,即 pattern='2C-BEB-29-*.csv',字符串格式。请注意,我在正确的目录中。

def pd_read_pattern(pattern):
files = glob.glob(pattern)

df = pd.DataFrame()
for f in files:
csv_file = open(f)
a = pd.read_csv(f,sep='\s+|;|,', engine='python')
#date column should be changed depending on patient id
a['date'] = str(csv_file.name).rsplit('29-',1)[-1].rsplit('.',1)[0]

#df = df.append(a)
#df = df[df['hf']!=0]


return df.reset_index(drop=True)

为了对所有用户 ID 应用上述代码,我已按以下方式读取 CSV 文件并将它们保存到列表中。为避免重复 ID,我已将此列表末尾的列表转换为集合。

import glob
lst=[]
for name in glob.glob('*.csv'):
if len(name)>15:
a = name.split('-',3)[0]+"-"+name.split('-',3)[1]+"-"+name.split('-',3)[2]+'-*'
lst.append(a)
lst = set(lst)

现在,在此示例格式中具有唯一 ID 的名称:'2C-BEB-29-*.csv'。在下面代码片段的帮助下,我正在尝试读取用户 ID。但是,我在 pd.read_csv 行中收到 unicode/decode 错误。你能帮我解决这个问题吗?

for file in lst:
#print(type(file))
files = glob.glob(file)
#print(files)
df = pd.DataFrame()
for f in files:
csv_file = open(f)
#print(f, type(f))
a = pd.read_csv(f,sep='\s+|;|,', engine='python')

#date column should be changed depending on patient id
#a['date'] = str(csv_file.name).rsplit(f.split('-',3)[2]+'-',1)[-1].rsplit('.',1)[0]

#df = df.append(a)
#df = df[df['hf']!=0]


#return df.reset_index(drop=True)

最佳答案

首先,

import chardet

然后,替换你的代码片段

a =  pd.read_csv(f,sep='\s+|;|,', engine='python')

这个

with open(f, 'rb') as file: 
encodings = chardet.detect(file.read())["encoding"]
a = pd.read_csv(f,sep='\s+|;|,', engine='python', encoding=encodings)

关于python - Pandas 读取多个文件时读取 CSV 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73647074/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com