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]))
The numpy.savetxt()
method has several parameters which are worth noting:
fmt : str or sequence of strs, optional
it is used to format the numbers in the array, see the doc for details on formatingdelimiter : str, optional
String or character separating columnsnewline : str, optional
String or character separating lines.
Let's take an example. I have an array of size (M, N)
, which consists of integer numbers in the range (0, 255). To save the array row-wise and show it nicely, we can use the following code:
import numpy as np
np.savetxt("my_array.txt", my_array, fmt="%4d", delimiter=",", newline="\n")
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
import numpy as np
a = [1,2,3]
b = np.array(a).reshape((1,3))
np.savetxt('a.txt',b,fmt='%d')
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')
import numpy
a = numpy.array([1,2,3])
with open(r'test.txt', 'w') as f:
f.write(" ".join(map(str, a)))
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)
just
' '.join(a)
and write this output to a file.
Source: Stackoverflow.com