對於python/pandas,我發現df.to_csv(fname)的工作速度爲每分鐘約100萬行。我有時可以將性能提高7倍,如下所示:將大型DataFrame輸出到CSV文件的最快方法是什麼?
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times faster for strings.
# Note - be careful. It doesn't add quotes and doesn't check
# for quotes or separators inside elements
# We've seen output time going down from 45 min to 6 min
# on a simple numeric 4-col dataframe with 45 million rows.
"""
if len(df.columns) <= 0:
return
Nd = len(df.columns)
Nd_1 = Nd - 1
formats = myformats[:] # take a copy to modify it
Nf = len(formats)
# make sure we have formats for all columns
if Nf < Nd:
for ii in range(Nf,Nd):
coltype = df[df.columns[ii]].dtype
ff = '%s'
if coltype == np.int64:
ff = '%d'
elif coltype == np.float64:
ff = '%f'
formats.append(ff)
fh=open(fname,'w')
fh.write(','.join(df.columns) + '\n')
for row in df.itertuples(index=False):
ss = ''
for ii in xrange(Nd):
ss += formats[ii] % row[ii]
if ii < Nd_1:
ss += sep
fh.write(ss+'\n')
fh.close()
aa=DataFrame({'A':range(1000000)})
aa['B'] = aa.A + 1.0
aa['C'] = aa.A + 2.0
aa['D'] = aa.A + 3.0
timeit -r1 -n1 aa.to_csv('junk1') # 52.9 sec
timeit -r1 -n1 df2csv(aa,'junk3',myformats=['%d','%.1f','%.1f','%.1f']) # 7.5 sec
注意:性能的提高取決於dtypes。 但總是如此(至少在我的測試中) to_csv()比非優化python執行速度慢得多。
如果我有4500萬行csv文件,然後:
aa = read_csv(infile) # 1.5 min
aa.to_csv(outfile) # 45 min
df2csv(aa,...) # ~6 min
問題:
What are the ways to make the output even faster?
What's wrong with to_csv() ? Why is it soooo slow ?
注:我測試使用本地驅動器上的大熊貓0.9.1完成在Linux服務器。
我剛剛使用內置的to_excel,然後使用to_csv DataFrame方法從DataFrame組中以批量方式導出約1.7K報告,並且部分報告(特別是較大的文件)出現損壞。我現在對這些內置程序頗感懷疑,並計劃爲我的工作流程自行創建自己的導出功能。 – 2013-03-14 19:00:20
@DavidMarx你能發佈一個損壞的文件,DataFrame和你的代碼的例子嗎?這將有助於我們極大地調試問題。謝謝。 – 2013-03-14 23:16:24
這是我爲我的辦公室設計的一種主力工具。我會看看我是否不能用對工作不敏感的數據複製問題。 – 2013-03-15 00:56:42