简体   繁体   中英

Why is True printed with leading whitespace in numpy array

I noticed that in NumPy 1.13.1 , when a dtype=np.bool_ array is printed the True values always have a leading whitespace.

>>> import numpy as np
>>> np.asarray([1, 0, 1, 1, 0], dtype=np.bool_)
array([ True, False,  True,  True, False], dtype=bool)
>>> #  ^             ^      ^
... # I would have expected: array([True, False, True, True, False], dtype=bool)
...
>>> str(np.asarray([0, 1, 1, 0], dtype=np.bool_))
'[False  True  True False]'
>>> #   ^     ^
... # Again I would have expected: '[False True True False]'
...
>>> repr(np.asarray([1, 1, 1, 0, 0], dtype=np.bool_))
'array([ True,  True,  True, False, False], dtype=bool)'
>>> #   ^      ^      ^
... # repr() does it too.

Is there any particular reason for formatting it like this?

This happens for float and bool arrays.

  • For float arrays with negative values the extra space ensures alignment (which is nice for multidimensional arrays) leaving space for the negative sign.

     >>> np.array([-4, 1, 2, -3], dtype=np.float64).reshape(2, 2) array([[-4., 1.], [ 2., -3.]]) 
  • For bool arrays with multiple values it ensures alignment between True and False , which are different lengths.

     >>> np.array([0, 1, 1, 0], dtype=np.bool_).reshape(2, 2) array([[False, True], [ True, False]], dtype=bool) 

There is no particular reason when it is not needed (ie all positive float values, single element bool array), and in this case it could be done without.

>>> np.array([4, 1, 2, 3], dtype=np.float64).reshape(2, 2)
array([[ 4.,  1.],
       [ 2.,  3.]])

There's an open PR #9130 on GitHub to make this print spacing more consistent when the additional spacing is not needed with some support, and so it may change in an upcoming version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM