将NumPy数组保存为文件,使用np.savetxt。

3

当我使用np.savetxt('file.txt', (arr1, arr2, arr3))时,如何将多个numpy数组保存到文件中的最佳方式?这些数组是按列而不是按行保存的,这使得将其导入Excel变得困难。如何以更标准的方式保存数组?

谢谢。


这取决于数组的维度。你可以先尝试将它们分组:arr=np.vstack((arr1,arr2,arr3)),然后再保存它。 - B. M.
1个回答

4
我几乎可以直接回答,这里概述了如何使用vstack从numpy中保存多个数组到文件的方法:http://rinocloud.github.io/rinocloud-tutorials/saving-data-with-numpy
使用vstack:
保存多个numpy数组到文件中。假设我们有一个想要保存到文件中的numpy数组。
x = np.random.random_integers(0, 10, size=10)
np.savetxt('test.txt', x)

它会生成以下内容的文件

0.0e+00
8.0e+00
7.0e+00
6.0e+00
1.0e+01
7.0e+00
9.0e+00
9.0e+00
0.0e+00
3.0e+00

这很好,基于列的表示意味着很容易导入到CSV兼容的程序中,如Excel、LabView、Matlab和Origin。

但是当我们想要保存两个或更多数组并确保文件仍然可以轻松地导入到不同的程序中时,会发生什么。

如果我们只是使用

x = np.random.random_integers(0, 10, size=10)
y = np.random.random_integers(0, 10, size=10)
z = np.random.random_integers(0, 10, size=10)

np.savetxt('test.txt', (x, y, z))

我们得到:
9.0e+00 9.0e+00 4.0e+00 2.0e+00 0.0e+00 8.0e+00 1.0e+01 2.0e+00 1.0e+00 9.0e+00
2.0e+00 3.0e+00 1.0e+00 9.0e+00 2.0e+00 5.0e+00 1.0e+01 2.0e+00 8.0e+00 3.0e+00
9.0e+00 8.0e+00 2.0e+00 7.0e+00 9.0e+00 0.0e+00 6.0e+00 0.0e+00 2.0e+00 3.0e+00
所以,我们可以使用numpy vstack
x = np.random.random_integers(0, 10, size=10)
y = np.random.random_integers(0, 10, size=10)
z = np.random.random_integers(0, 10, size=10)

np.savetxt('test.txt', np.vstack((x, y, z)).T)

这将生成一个名为test.txt的文件,其中包含以下内容:
9.0e+00 2.0e+00 9.0e+00
9.0e+00 3.0e+00 8.0e+00
4.0e+00 1.0e+00 2.0e+00
2.0e+00 9.0e+00 7.0e+00
0.0e+00 2.0e+00 9.0e+00
8.0e+00 5.0e+00 0.0e+00
1.0e+01 1.0e+01 6.0e+00
2.0e+00 2.0e+00 0.0e+00
1.0e+00 8.0e+00 2.0e+00
9.0e+00 3.0e+00 3.0e+00
这样更加便携,并且可以轻松地导入到诸如Excel之类的程序中。
要使用numpy再次读取文件并转换为数组,请使用以下代码:
x, y, z = np.loadtxt('test.txt').T

这是一种快速简便的方法,可使用numpy将数组存储到文件中并从文件中读取数组。它使文件具有便于与其他程序一起使用的可移植性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接