【问题标题】:fast formatted file output of numpy arraynumpy数组的快速格式化文件输出
【发布时间】:2019-12-12 14:26:15
【问题描述】:

我有一个 large numpy 数组,我想将它转储到使用 ASCII 格式的文件中。我想指定格式。这有效:

import numpy

a = numpy.random.rand(5)
fmt = "{:.11e}\n"

with open("out.dat", "w") as f:
    for item in a:
        f.write(fmt.format(item))

但速度很慢,因为我手动循环了a 的所有条目。有没有办法只在一次write 操作中处理这个问题?

【问题讨论】:

  • (fmt*len(a)).format(*a.tolist()) 是格式化整个数组的更快方法。

标签: python numpy io format


【解决方案1】:

提供的 RAM 不是问题,您可以尝试将数组格式化为字符串,然后将其导出:

a_str = np.array2string(a, formatter={'float_kind':lambda x: "%.11f" % x}, separator='\n', threshold=np.inf)[1:-1]
with open("out.dat", "w") as f:
    f.write(a_str)

【讨论】:

  • 小心大数组省略号
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
相关资源
最近更新 更多