我有数据存储在逗号分隔的txt文件中。其中一列表示日期时间。
我需要将每个列加载到单独的numpy数组中(并将日期解码为python datetime对象)。
最快的方法是什么(就运行时间而言)?
注意。这些文件是几百MB的数据,目前需要几分钟才能加载进去。
例如mydata.txt15,3,0,2003-01-01 00:00:00,12.2
15,4.5,0,2003-01-01 00:00:00,13.7
15,6,0,2003-01-01 00:00:00,18.4
15,7.5,0,2003-01-01 00:00:00,17.9
15,9,0,2003-01-01 00:00:00,17.7
15,10.5,0,2003-01-01 00:00:00,16.3
15,12,0,2003-01-01 00:00:00,17.2
这是我当前的代码(它工作正常,但速度很慢):import csv
import datetime
import time
import numpy
a=[]
b=[]
c=[]
d=[]
timestmp=[]
myfile = open('mydata.txt',"r")
# Read in the data
csv_reader = csv.reader(myfile)
for row in csv_reader:
a.append(row[0])
b.append(row[1])
c.append(row[2])
timestmp.append(row[3])
d.append(row[4])
a = numpy.array(a)
b = numpy.array(b)
c = numpy.array(c)
d = numpy.array(d)
# Convert Time string list into list of Python datetime objects
times = []
time_format = "%Y-%m-%d %H:%M:%S"
for i in xrange(len(timestmp)):
times.append(datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestmp[i], time_format))))
有没有更有效的方法来做到这一点?
非常感谢您的帮助-谢谢!
(编辑:最后的瓶颈是日期时间转换,而不是像我原先假设的那样读取文件。)
本文探讨如何快速读取数百MB大小的逗号分隔txt文件,将数据加载到numpy数组中,并将日期字符串转换为Python datetime对象。现有的解决方案虽然有效,但在处理大文件时速度较慢,寻求更高效的实现方法。
1万+

被折叠的 条评论
为什么被折叠?



