python - 将大型 DataFrame 输出到 CSV 文件的最快方法是什么?

标签 python performance pandas output

对于 python/pandas,我发现 df.to_csv(fname) 以每分钟约 100 万行的速度工作。我有时可以像这样将性能提高 7 倍:

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

注意:性能的提高取决于数据类型。 但这总是正确的(至少在我的测试中) 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 ?

注意:我的测试是在 Linux 服务器的本地驱动器上使用 pandas 0.9.1 完成的。

最佳答案

列夫。 Pandas 重写了 to_csv 以大幅提高 native 速度。该过程现在是 i/o 绑定(bind)的,解决了许多微妙的 dtype 问题和引用案例。这是我们与 0.10.1(即将发布的 0.11)版本相比的性能结果。这些以 ms 为单位,比率越低越好。

Results:
                                            t_head  t_baseline      ratio
name                                                                     
frame_to_csv2 (100k) rows                 190.5260   2244.4260     0.0849
write_csv_standard  (10k rows)             38.1940    234.2570     0.1630
frame_to_csv_mixed  (10k rows, mixed)     369.0670   1123.0412     0.3286
frame_to_csv (3k rows, wide)              112.2720    226.7549     0.4951

因此,单个 dtype(例如 float )的吞吐量,不太宽约为 20M 行/分钟,这是您上面的示例。

In [12]: df = pd.DataFrame({'A' : np.array(np.arange(45000000),dtype='float64')}) 
In [13]: df['B'] = df['A'] + 1.0   
In [14]: df['C'] = df['A'] + 2.0
In [15]: df['D'] = df['A'] + 2.0
In [16]: %timeit -n 1 -r 1 df.to_csv('test.csv')
1 loops, best of 1: 119 s per loop

关于python - 将大型 DataFrame 输出到 CSV 文件的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15417574/

相关文章:

linux - 绩效评估中的异常值

python - 在 app.yaml 中定义路由与在 AppEngine 中的 WSGIApplication 中定义一个大型映射相比,是否有性能提升?

python - 将 UTF-8 字符串转换为 Python 中的字符串

python - 如何检查我是否在Python的shell(有终端)中运行?

database - 识别覆盖索引中不需要的列的方法有哪些?

python - 如何根据日期时间值创建列?

python-3.x - 在python pandas中基于df值比较创建派生字段

python - 为什么 `in` 在 Series 包含字符串时不搜索值

python - 使用 SSL 在本地运行适用于 Python 的 Heroku 示例应用程序时出现问题

python - python 中的函数 "integrate.quad"和 R 中的 "integral",'integrate' 给出错误结果