我试图从大型csv文件(大约250 000行)填充数组列表,但它需要很长时间。我确信有办法让这个过程更快,但我不知道怎么做!
以下是代码:
import csv
import numpy as np
energy = []
ondeIG =[]
time =[]
envelope = []
with open('file.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
time = np.hstack([time, row['Time']])
energy = np.hstack([energy, row['Energy']])
ondeIG = np.hstack([ondeIG, row['OndeIG']])
envelope = np.hstack([envelope, row['envelope']])
谢谢!
答案 0 :(得分:3)
np.hstack()
每次构建一个新的ndarray是昂贵的。您可以使用append:
with open('file.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
time.append(row['Time'])
energy.append(row['Energy'])
ondeIG.append(row['OndeIG'])
envelope.append(row['envelope'])
答案 1 :(得分:0)
要从csv文件导入数据,请查看pandas,更具体地说是pandas.read_csv()
在这里你需要花费大量时间,因为你在每次迭代时重建一个数组(4个数组,偶数)。