6

When I print a numpy array via:

print('Array: ', A)

the result is badly formatted:

Array: [[0.0000 0.5000]
 [0.0000 0.3996]]

Instead I would like to align 'correctly':

Array: [[0.0000 0.5000]
        [0.0000 0.3996]]
0

3 Answers 3

6

NumPy provides a function for that: np.array2string

Use it like this to specify your prefix (length):

>>> print('Array:', np.array2string(A, prefix='Array: '))
Array: [[0.     0.5   ]
        [0.     0.3996]]

To understand, what this function does, see the output of it alone:

>>> print(np.array2string(A, prefix='Array: '))
[[0.     0.5   ]
        [0.     0.3996]]

So it simply indents the lines after the first one with the length of the prefix. The prefix itself is not printed.

2

The simplest way to improve the display is to separate the label and array prints:

In [13]: print('Array:');print(np.arange(4).reshape(2,2))
Array:
[[0 1]
 [2 3]]

In

In [14]: print('Array', np.arange(4).reshape(2,2))
Array [[0 1]
 [2 3]]

the print combines the string with the str format of the array:

In [15]: print('Array', str(np.arange(4).reshape(2,2)))
Array [[0 1]
 [2 3]]
In [16]: str(np.arange(4).reshape(2,2))
Out[16]: '[[0 1]\n [2 3]]'

str(A) is done independently of the larger context, so just has the minor indent, not the big one you want.

To get closer to your desired result you'll have to split and combine those strings yourself.


Variants producing the same thing:

In [19]: print('Array\n{}'.format(np.arange(4).reshape(2,2)))
Array
[[0 1]
 [2 3]]

In [22]: print('Array',np.arange(4).reshape(2,2),sep='\n')
Array
[[0 1]
 [2 3]]

Here's what I have in mind with splitting and rebuilding:

In [26]: alist = str(np.arange(6).reshape(3,2)).splitlines()
In [27]: alist
Out[27]: ['[[0 1]', ' [2 3]', ' [4 5]]']
In [28]: header = 'Array: '; offset = '       '
In [29]: astr = [header + alist[0]]
In [30]: for row in alist[1:]:
    ...:     astr.append(offset + row)
    ...:     
In [31]: astr
Out[31]: ['Array: [[0 1]', '        [2 3]', '        [4 5]]']
In [32]: print('\n'.join(astr))
Array: [[0 1]
        [2 3]
        [4 5]]
0

Duplicated from: How do I print an aligned numpy array with (text) row and column labels?

But please refer to this response by Andy P, note that you can also print it all without labels just as fine

This code is essentially an implementation of scoffey's above, but it doesn't have the three character limitation and is a bit more powerful. Here's my code:

    def format__1(digits,num):
        if digits<len(str(num)):
            raise Exception("digits<len(str(num))")
        return ' '*(digits-len(str(num))) + str(num)
    def printmat(arr,row_labels=[], col_labels=[]): #print a 2d numpy array (maybe) or nested list
        max_chars = max([len(str(item)) for item in flattenList(arr)+col_labels]) #the maximum number of chars required to display any item in list
        if row_labels==[] and col_labels==[]:
            for row in arr:
                print '[%s]' %(' '.join(format__1(max_chars,i) for i in row))
        elif row_labels!=[] and col_labels!=[]:
            rw = max([len(str(item)) for item in row_labels]) #max char width of row__labels
            print '%s %s' % (' '*(rw+1), ' '.join(format__1(max_chars,i) for i in col_labels))
            for row_label, row in zip(row_labels, arr):
                print '%s [%s]' % (format__1(rw,row_label), ' '.join(format__1(max_chars,i) for i in row))
        else:
            raise Exception("This case is not implemented...either both row_labels and col_labels must be given or neither.")

running

    import numpy
    x = numpy.array([[85, 86, 87, 88, 89],
                     [90, 191, 192, 93, 94],
                     [95, 96, 97, 98, 99],
                     [100,101,102,103,104]])
    row_labels = ['Z', 'Y', 'X', 'W']
    column_labels = ['A', 'B', 'C', 'D', 'E']
    printmat(x,row_labels=row_labels, col_labels=column_labels)

gives

         A   B   C   D   E
    Z [ 85  86  87  88  89]
    Y [ 90 191 192  93  94]
    X [ 95  96  97  98  99]
    W [100 101 102 103 104]

This would also be the output if 'x' were just a nested python list instead of a numpy array.

1
  • Please also note that with this code if you want labels you need to use both column and row labels. Only one of them won't work Jul 13, 2018 at 14:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.