Numpy Array printing algorithms

Tony Yu tsyu80 at gmail.com
Tue Jun 3 01:58:58 EDT 2014


On Tue, Jun 3, 2014 at 12:00 AM, Juan Nunez-Iglesias <jni.soma at gmail.com>
wrote:

> Hi All,
>
> This is more suited for a numpy list but thought I'd try the home crowd
> first. Does anyone know how numpy decides to print arrays? It is a pain
> getting doctests to pass without knowing the system. Example:
>
> In [15]: lifio.parse_series_name(name2)[1][:5]
> Out[15]: array([ 63. ,  63.5,  64. ,  64.5,  65. ])
>
> In [16]: lifio.parse_series_name(name2, 1)[1][:5]
> Out[16]: array([ 63.,  64.,  65.,  66.,  67.])
>
> Note:
>
> It goes 63.<space>,<space-space>63.5,<space-space>64.<space> etc. Note
> also the space after the opening brace but not the closing brace.
> Basically, you can't go by PEP8, so it's a pain predicting what the actual
> printout is going to be. I get the space after the . so that the .5's will
> align, but what about the leading spaces?
>
> Juan.
>

Part of what you're looking for is set by `np.set_printoptions`. For
example, you can write something like

In [31]: np.set_printoptions(formatter={'all': lambda x: '|{}'.format(x)},
precision=3)

In [32]: a
Out[32]:
array([|10.0, |10.5, |11.0, |11.5, |12.0, |12.5, |13.0, |13.5, |14.0,
       |14.5, |15.0, |15.5, |16.0, |16.5, |17.0, |17.5, |18.0, |18.5,
       |19.0, |19.5, |20.0])

In [33]: print a
[|10.0 |10.5 |11.0 |11.5 |12.0 |12.5 |13.0 |13.5 |14.0 |14.5 |15.0 |15.5
 |16.0 |16.5 |17.0 |17.5 |18.0 |18.5 |19.0 |19.5 |20.0]

Note that `repr` adds commas after values (and the `array(` prefix), while
`str` doesn't. There's some magic in the default formatter that I haven't
dug into. Somehow, it's able to read all the values beforehand so that it
can determine the maximum width needed to align values. So for example, you
might write this

In [38]: a = np.array([1, 10, 100, 1000])

and get this as output

In [39]: print a
[|1 |10 |100 |1000]

But what you really wanted was this

In [40]: np.set_printoptions(formatter={'all': lambda x:
'|{:4}'.format(x)}, precision=3)

In [41]: print a
[|   1 |  10 | 100 |1000]

Ideally that `{:4}` could be determined after looking at the entire array.
That part is a bit of a mystery to me.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/scikit-image/attachments/20140603/226fed20/attachment.html>


More information about the scikit-image mailing list