Reputation: 2405
i want formatting a numpy array and save it in a *.txt file
The numpy array looks like this:
a = [ 0.1 0.2 0.3 0.4 ... ] , [ 1.1 1.2 1.3 1.4 ... ] , ...
and the output *.txt should looks like 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 to do that.
thank you.
well jaba thank you. I fixed your answer a little bit
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()
do you thinks thats ok?!
Upvotes: 3
Views: 256
Reputation:
Rather simple:
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")
And the 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 a lot of disk writes. If your array is large, this can be pretty inefficient. The number of writes can be reduced, though, such as:
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']))
You can reduce the number of writes further to just one by constructing one large string and writing it at the end, but in the case in which this would be truly beneficial (i.e. a huge array), you then run into memory problems from constructing a huge string. Anyway, it's up to you.
Upvotes: 4