I want to convert a = [1,2,3,4,5]
into a_string = "1 2 3 4 5"
. The real numpy array is quite big (50000x200) so I assume using for loops
is too slow.
7 Answers
np.savetxt
Python 3 (see also):
import numpy as np
import sys
a = np.array([0.0, 1.0, 2.0, 3.0])
np.savetxt(sys.stdout.buffer, a)
Python 2:
import numpy as np
import sys
a = np.array([0.0, 1.0, 2.0, 3.0])
np.savetxt(sys.stdout, a)
Output:
0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
Control the precision
Use fmt
:
np.savetxt(sys.stdout, a, fmt="%.3f")
output:
0.000
1.000
2.000
3.000
or:
np.savetxt(sys.stdout, a, fmt="%i")
output:
0
1
2
3
Get a string instead of printing
Python 3:
import io
bio = io.BytesIO()
np.savetxt(bio, a)
mystr = bio.getvalue().decode('latin1')
print(mystr, end='')
We use latin1
because the docs tell us that it is the default encoding used.
Python 2:
import StringIO
sio = StringIO.StringIO()
np.savetxt(sio, a)
mystr = sio.getvalue()
print mystr
All in one line
Or if you really want all in one line:
a = np.array([0.0, 1.0, 2.0, 3.0])
np.savetxt(sys.stdout, a, newline=' ')
print()
Output:
0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00 3.000000000000000000e+00
TODO: there is a trailing space. The only solution I see is to save to a string and strip.
Tested on Python 2.7.15rc1 and Python 3.6.6, numpy 1.13.3
Maybe a bit hacky, but I just slice them off after using np.array2string
so:
import numpy as np
a = np.arange(0,10)
a_str = np.array2string(a, precision=2, separator=', ')
print(a_str[1:-1])
Result:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
np.array2string
has lots of options also, so you can set your column width which can be very helpful with lots of data:
a = np.arange(0,15)
a_str = np.array2string(a, precision=2, separator=', ', max_line_width=15)
print(' ' + a_str[1:-1])
Gives:
0, 1, 2,
3, 4, 5,
6, 7, 8,
9, 10, 11,
12, 13, 14
And it will smartly split at the array elements. Note the space appended to the beginning of the string to account for aligning the first row after removing the initial bracket.
If you have a numpy array to begin with rather than a list (since you mention a "real numpy array" in your post) you could use re.sub
on the string representation of the array:
print(re.sub('[\[\]]', '', np.array_str(a)))
Again, this is assuming your array a
was a numpy array at some point. This has the advantage of working on matrices as well.
Numpy provides two functions for this array_str and array_repr -- either of which should fit your needs. Since you could use either, here's an example of each:
>>> from numpy import arange, reshape, array_str
>>> M = arange(10).reshape(2,5)
>>> M
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> array_str(M)
'[[0 1 2 3 4]\n [5 6 7 8 9]]'
>>> array_repr(M)
'array([[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9]])'
These two functions are both highly optimized and, as such, should be preferred over a function you might write yourself. When dealing with arrays this size, I'd imagine you'd want all the speed you can get.
If you are dealing with floating-point numbers and two dimensional arrays you can also do the following:
import numpy as np
np.random.seed(77)
def my_print(x):
for row in x:
print(' '.join(map(lambda x: "{:.3f}\t".format(x), row)))
if __name__ == '__main__':
x = np.random.random(size=(3, 9))
my_print(x)
which outputs:
0.919 0.642 0.754 0.139 0.087 0.788 0.326 0.541 0.240
0.545 0.401 0.715 0.837 0.588 0.296 0.281 0.706 0.423
0.057 0.747 0.452 0.176 0.049 0.292 0.067 0.751 0.064
writeline
. – Framester