While there are a few questions and answers out there which come close to what I am looking for, I am wondering if there isn't a more elegant solution to this specific problem: I have a numpy (2D) array and want to print it row by row together with the row number up front - and of course nicely formatted.
This code does the printing, straightforward but without formatting:
import numpy as np
A = np.zeros((2,3))
for i in range(2):
print i, A[i]
I can also produce formatted output by building the formatted string anew in each line:
for i in range(2):
print "%4i "%(i)+" ".join(["%6.2f"%(v) for v in A[i]])
While this works, I figured it may be more readable and perhaps more efficient(?) to build the format string only once and then "paste" the numbers in for each line:
NVAR=A.shape[1]
fmt = "%4i" + NVAR*" %6.2f"
for i in range(2):
print fmt % (i, A[i])
This fails, because the formatted print expects a tuple with float elements, but A[i] is an ndarray. Thus, my questions really boils down to "How can I form a tuple out of an integer value and a 1-D ndarray?". I did try:
tuple( [i].extend([v for v in A[i]]) )
but that doesn't work (this expression yields None, even though [v for v in A[i]]
works correctly).
Or am I only still too much thinking FORTRAN here?
You can convert the array elements directly to a tuple using the tuple
constructor :
for i in range(2):
print fmt % ((i, ) + tuple(A[i]))
Here, +
represents tuple concatenation.
Also, if you're coming from FORTRAN you might not yet know about enumerate
, which can be handy for this type of loop operation :
for i, a in enumerate(A):
print fmt % ((i, ) + tuple(a))
You could combine this with itertools.chain
to flatten the pairs from enumerate :
import itertools
for i, a in enumerate(A):
print fmt % tuple(itertools.chain((i, ), a))
These are all probably overkill for what you're trying to do here, but I just wanted to show a few more ways of doing it.