3
我想格式化numpy的陣列,並將其保存在一個* .txt文件格式化numpy的陣列,並保存到* .TXT
的numpy的陣列看起來像這樣:
a = [ 0.1 0.2 0.3 0.4 ... ] , [ 1.1 1.2 1.3 1.4 ... ] , ...
和輸出* .txt應該看起來像這樣:
0 1:0.1 2:0.2 3:0.3 4:0.4 ...
0 1:1.1 2:1.2 3:1.3 1:1.4 ...
...
不知道該怎麼做。
謝謝。
井jaba謝謝。我固定你的答案一點點
import numpy as np
a = np.array([[1,3,5,6], [4,2,4,6], [6,3,2,6]])
ret = ""
for i in range(a.shape[0]):
ret += "0 "
for j in range(a.shape[1]):
ret += " %s:%s" % (j+1,float(a[i,j])) #have a space between the numbers for better reading and i think it should starts with 1 not with 0 ?!
ret +="\n"
fd = open("output.sparse", "w")
fd.write(ret)
fd.close()
你認爲那可以嗎?