2013-07-19 31 views
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() 

你认为那可以吗?

回答

4

相当简单:

import numpy as np 

a = np.array([[0.1, 0.2, 0.3, 0.4], [1.1, 1.2, 1.3, 1.4], [2.1, 2.2, 2.3, 2.4]]) 

with open("array.txt", 'w') as h: 
    for row in a: 
     h.write("0") 
     for n, col in enumerate(row): 
      h.write("\t{0}:{1}".format(n+1, col)) # you can change the \t (tab) character to a number of spaces, if that's what you require 
     h.write("\n") 

和输出:

0  1:0.1 2:0.2 3:0.3 4:0.4 
0  1:1.1 2:1.2 3:1.3 4:1.4 
0  1:2.1 2:2.2 3:2.3 4:2.4 

我原来的例子涉及到大量的磁盘写操作。如果你的数组很大,这可能非常低效。写入次数可以减少,但是,如:

with open("array.txt", 'w') as h: 
    for row in a: 
     row_str = "0" 
     for n, col in enumerate(row): 
      row_str = "\t".join([row_str, "{0}:{1}".format(n+1, col)]) 
     h.write(''.join([row_str, '\n'])) 

您可以通过构建一个大的字符串,并在末尾写这进一步降低写入的数量只有一个,但在情况下,此将是真正有益的(即一个巨大的数组),然后你从构建一个巨大的字符串到内存问题。无论如何,这取决于你。