如何将n维数组(Python Numpy)导出为文本文件?
问题描述:
我有矩阵,它表示为2维数组。 看来我可以使用numpy.ndarray.tofile将其导出到文本文件中,但它只是在一行中生成所有内容。 如何获得矩阵格式的文本文件(比如,一行是矩阵中的一行)? 像如何将n维数组(Python Numpy)导出为文本文件?
1 2 3
4 5 6
7 8 9
,而不是
1 2 3 4 5 6 7 8 9
答
with open('path/to/file', 'w') as outfile:
for row in matrix:
outfile.write(' '.join([str(num) for num in row]))
outfile.write('\n')
答
咨询这个帖子有关编写numpy的阵列到文件:Write multiple numpy arrays to file
代码应该是这样的:
#data is a numpy array
data = numpy.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
# Save the array back to the file
np.savetxt('test.txt', data)
这产生以下(几乎是人类可读的)输出:
1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00 6.000000000000000000e+00
7.000000000000000000e+00 8.000000000000000000e+00 9.000000000000000000e+00