我有一个相当大的 csv 文件 (700mb),其组装如下:
qCode Date Value A_EVENTS 11/17/2014 202901 A_EVENTS 11/4/2014 801 A_EVENTS 11/3/2014 2.02E+14 A_EVENTS 10/17/2014 203901 etc.
I am parsing this file to get specific values, and then using DF.loc to populate a pre-existing DataFrame, i.e. the code:
for line in fileParse:
code=line[0]
for point in fields:
if(point==code[code.find('_')+1:len(code)]):
date=line[1]
year,quarter=quarter_map(date)
value=float(line[2])
pos=line[0].find('_')
ticker=line[0][0:pos]
i=ticker+str(int(float(year)))+str(int(float(quarter)))
df.loc[i,point]=value
else:
pass
我的问题是 .loc 是向现有 DataFrame 添加值的最有效方式吗?由于此操作似乎需要 10 多个小时...
fyi 字段是 DF 中的列(我感兴趣的值),索引 (i) 是一个字符串...
谢谢
请您参考如下方法:
不,您不应该逐行构建数据框。每次执行此操作时,都必须复制整个数据帧(它没有就地扩展),因此您使用的是 n + (n - 1) + (n - 2) + ... + 1, O(n^2), memory (必须进行垃圾收集)...这太糟糕了,因此要花费数小时!
您想使用read_csv,您有几个选择:
一次读入整个文件(即使只有几 gig 的 ram,这应该也能达到 700mb)。
pd.read_csv('your_file.csv')以 block 的形式读入 csv,然后将它们粘合在一起(在内存中)...老实说,我认为这实际上不会比上面的方法使用更少的内存,但如果你正在做一些修改,这通常很有用在这一步。
pd.concat(pd.read_csv('foo.csv', chunksize=100000)) # not sure what optimum value is for chunksize分块读取 csv 并将它们保存到 pytables(而不是内存中),如果您的数据多于内存(并且您已经购买了更多内存),那么使用 pytables/hdf5!
store = pd.HDFStore('store.h5') for df in pd.read_csv('foo.csv', chunksize=100000): store.append('df', df)
