Saving numpy array to txt file row wise

2019-03-11 16:37发布

I have an numpy array of form

a = [1,2,3]

which I want to save to a .txt file such that the file looks like:

1 2 3

If I use numpy.savetxt then I get a file like:

1
2
3

There should be a easy solution to this I suppose, any suggestions?

9条回答
Emotional °昔
2楼-- · 2019-03-11 16:53
import numpy
a = numpy.array([1,2,3])

with open(r'test.txt', 'w') as f:
    f.write(" ".join(map(str, a)))
查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-11 16:53

Very very easy: [1,2,3]

A list is like a column.

1
2
3

If you want a list like a row, double corchete:

[[1, 2, 3]]  --->    1, 2, 3

and

[[1, 2, 3], [4, 5, 6]]  ---> 1, 2, 3
                             4, 5, 6

Finally:

np.savetxt("file", [['r1c1', 'r1c2'], ['r2c1', 'r2c2']], delimiter=';', fmt='%s')

Note, the comma between square brackets, inner list are elements of the outer list

查看更多
趁早两清
4楼-- · 2019-03-11 16:54

I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:

numpy.savetxt(filename, [a], delimiter='\t')
查看更多
Lonely孤独者°
5楼-- · 2019-03-11 16:54

I know this is old, but none of these answers solved the root problem of numpy not saving the array row-wise. I found that this one liner did the trick for me:

b = np.matrix(a)
np.savetxt("file", b)
查看更多
霸刀☆藐视天下
6楼-- · 2019-03-11 16:56

If numpy >= 1.5, you can do:

# note that the filename is enclosed with double quotes,
# example "filename.txt"

numpy.savetxt("filename", a, newline=" ")

Edit

several 1D arrays with same length

a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
numpy.savetxt(filename, (a,b), fmt="%d")

# gives:
# 1 2 3
# 4 5 6

several 1D arrays with variable length

a = numpy.array([1,2,3])
b = numpy.array([4,5])

with open(filename,"w") as f:
    f.write("\n".join(" ".join(map(str, x)) for x in (a,b)))

# gives:
# 1 2 3
# 4 5
查看更多
Ridiculous、
7楼-- · 2019-03-11 16:59

An alternative answer is to reshape the array so that it has dimensions (1, N) like so:

savetext(filename, a.reshape(1, a.shape[0]))
查看更多
登录 后发表回答