[英]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.