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.

其他提示

You can convert the numpy array to a list with tolist() first.

for i in range(2):
    print fmt % tuple([i] + A[i].tolist())

The reason for your error is that extending a list yields no return value.

>>> x = range(5)
>>> x.extend([5, 6])
>>> x
[0, 1, 2, 3, 4, 5, 6]

The + operator is for concatenation of lists.

Here is a simple solution:

import numpy as np
A = np.random.rand(200,3)
for i in xrange(98, 102):
    print '{0:4d} {1}'.format(i, A[i]) #'4d' reserves space for 4 digits
                                       # Modify to the maximum # of rows

The output looks like:

  98 [ 0.40745341  0.29954899  0.21880649]
  99 [ 0.23325155  0.81340095  0.57966024]
 100 [ 0.24145552  0.12387366  0.0384011 ]
 101 [ 0.76432552  0.68382022  0.93935336]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top