繁体   English   中英

如何将n维数组(Python Numpy)导出到文本文件中?

[英]How to export the n dimensional array(Python Numpy) into text file?

我有矩阵,呈现为二维数组。 似乎我可以使用numpy.ndarray.tofile将其导出到文本文件中,但它只是在一行中生成所有内容。 如何以矩阵格式获取文本文件(例如,一行是矩阵中的一行)? 喜欢

1 2 3
4 5 6
7 8 9

代替

1 2 3 4 5 6 7 8 9

请参阅这篇关于将numpy数组写入文件的帖子: 将多个numpy数组写入文件

代码应该是这样的:

#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
with open('path/to/file', 'w') as outfile:
    for row in matrix:
        outfile.write(' '.join([str(num) for num in row]))
        outfile.write('\n')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM