8

What is an idiomatic way to write a Numpy 2D Array to stdout? e.g. 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.]]

That I would like outputted as:

2.0 0.0 0.0
0.0 2.0 0.0
0.0 0.0 4.0

I can do this by converting to a nested list, and then joining the list elements:

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

but would like something like:

a.tofile( sys.stdout )

(except this gives a syntax error).

1 Answer 1

19

How 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, ...).

Sign up to request clarification or add additional context in comments.

1 Comment

Why sys.stdout.buffer should be used in python 3+ instead of sys.stdout?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.