Using numpy to write an array to stdout

What is the idiomatic way to write a Numpy 2D array to stdout? for example I have an array

a = numpy.array([[2., 0., 0.], [0., 2., 0.], [0., 0., 4.]]) [[ 2. 0. 0.] [ 0. 2. 0.] [ 0. 0. 4.]] 

What I would like to receive as:

 2.0 0.0 0.0 0.0 2.0 0.0 0.0 0.0 4.0 

I can do this by going to the nested list and then attaching the list items:

 print( '\n'.join( [ ' '.join( [ str(e) for e in row ] ) for row in a.tolist() ] ) ) 

but I would like something like:

 a.tofile( sys.stdout ) 

(except that it gives a syntax error).

+6
source share
1 answer

What about the following code?

 >>> a = numpy.array([[2., 0., 0.], [0., 2., 0.], [0., 0., 4.]]) >>> numpy.savetxt(sys.stdout, a, fmt='%.4f') 1.0000 2.0000 3.0000 0.0000 2.0000 0.0000 0.0000 0.0000 4.0000 

In Python 3+, use numpy.savetxt(sys.stdout.buffer, ...) .

+14
source

All Articles