Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python print aligned numpy array

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]]
like image 744
Hyperplane Avatar asked Jul 13 '18 14:07

Hyperplane


2 Answers

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.

like image 184
John Avatar answered Nov 11 '22 03:11

John


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]]
like image 30
hpaulj Avatar answered Nov 11 '22 03:11

hpaulj