2014-12-19 1453 views
1

我有矩陣,它表示爲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 

回答

-1
with open('path/to/file', 'w') as outfile: 
    for row in matrix: 
     outfile.write(' '.join([str(num) for num in row])) 
     outfile.write('\n') 
4

諮詢這個帖子有關編寫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 
相關問題