在python中构建文本文件的更快方法



我有两个 3d numpy 数组,称它们为 a 和 b,512x512x512。我需要将它们写入文本文件:

a1 b1
a2 b2
a3 b3
...

这可以通过三重循环来实现:

lines = []
for x in range(nx):
    for y in range(ny):
        for z in range(nz):
            lines.append('{} {}'.format(a[x][y][z], b[x][y][z])
print('n'.join(lines))

但这非常慢(10分钟,而我更喜欢在mac Pro上几秒钟(。

我正在使用python 3.6,最新的numpy,并且很乐意使用其他库,构建扩展,任何必要的东西。更快获得此消息的最佳方法是什么?

您可以使用

np.stack并将数组的形状调整为(-1,2((两列(数组,然后使用np.savetxt

a = np.arange(8).reshape(2,2,2)
b = np.arange(8, 16).reshape(2,2,2)
np.stack([a, b], axis=-1).reshape(-1, 2)
#array([[ 0,  8],
#       [ 1,  9],
#       [ 2, 10],
#       [ 3, 11],
#       [ 4, 12],
#       [ 5, 13],
#       [ 6, 14],
#       [ 7, 15]])

然后,您可以将文件另存为:

np.savetxt("*.txt", np.stack([a, b], axis=-1).reshape(-1, 2), fmt="%d")
你可以

使用 flatten(( 和 dstack((,参见下面的示例

a = np.random.random([5,5,5]).flatten()
b = np.random.random([5,5,5]).flatten()
c = np.dstack((a,b))
print c

将导致

[[[ 0.31314428  0.35367513]
  [ 0.9126653   0.40616986]
  [ 0.42339608  0.57728441]
  [ 0.50773896  0.15861347]
....

不知道这三个数组中有多少类型的数据,就很难理解您的问题,但看起来numpy.savetxt对您有用。

以下是它的工作原理:

import numpy as np
a = np.array(range(10))
np.savetxt("myfile.txt", a)

这是文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

最新更新