如何从多个文件中读取同一列并将其收集到数组中

问题描述 投票:0回答:1

我有 9 个 csv 文件,每个文件包含相同数量的列 (61) 以及相同的列标题。这些文件基本上是相互跟进的。每列都属于一个信号读数,该信号读数已经记录了很长一段时间,因此分为多个文件。我需要绘制每一列收集的数据的图表。为此,我想一次从所有文件中读取一列,并将数据存储到一个数组中,并根据时间绘制图表。 由于数据负载太大,系统一个月内每 5 秒读取一次数据,我想每 30 分钟读取一次数据,相当于每 362 行读取 1 行。

我尝试在不跳过行的情况下绘制所有内容,但由于数据加载,这需要很长时间。

file_list = glob.glob('*.csv')
cols = [0,1] # add more columns here

df = pd.DataFrame()

for f in file_list:
    
    df = df.append(
        pd.read_csv(f, delimiter='\s+', header=None, usecols=cols),
        ignore_index=True,    
    )

arr = df.values

这就是我尝试从多个文件中仅读取特定列的方法,但我收到此消息:“Usecols 与列不匹配,需要但未找到的列:[1]”

arrays pandas csv multiple-columns
1个回答
0
投票

下面的命令将执行并行读取,然后进行串联。假设

file_list
包含可以使用下面的
read_file
函数读取的文件列表

import multiprocessing as mp


def read_file(file):
    return pd.read_csv(file)


pool = mp.Pool(mp.cpu_count())  # one worker per CPU. You can try other things
df = pd.concat(pool.map(read_file, file_list)
pool.terminate()
pool.join()
© www.soinside.com 2019 - 2024. All rights reserved.