i want formatting numpy array , save in *.txt file
the numpy array looks this:
a = [ 0.1 0.2 0.3 0.4 ... ] , [ 1.1 1.2 1.3 1.4 ... ] , ... and output *.txt should looks this:
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 ... ... don't know how that.
thank you.
well jaba thank you. fixed answer little bit
import numpy np = np.array([[1,3,5,6], [4,2,4,6], [6,3,2,6]]) ret = "" in range(a.shape[0]): ret += "0 " j in range(a.shape[1]): ret += " %s:%s" % (j+1,float(a[i,j])) #have space between numbers better reading , think should starts 1 not 0 ?! ret +="\n" fd = open("output.sparse", "w") fd.write(ret) fd.close() do thinks thats ok?!
rather simple:
import numpy np = 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]]) open("array.txt", 'w') h: row in a: h.write("0") n, col in enumerate(row): h.write("\t{0}:{1}".format(n+1, col)) # can change \t (tab) character number of spaces, if that's require h.write("\n") and output:
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 my original example involves lot of disk writes. if array large, can pretty inefficient. number of writes can reduced, though, such as:
with open("array.txt", 'w') h: row in a: row_str = "0" n, col in enumerate(row): row_str = "\t".join([row_str, "{0}:{1}".format(n+1, col)]) h.write(''.join([row_str, '\n'])) you can reduce number of writes further 1 constructing 1 large string , writing @ end, in case in beneficial (i.e. huge array), run memory problems constructing huge string. anyway, it's you.
Comments
Post a Comment