How to create a numpy array of all True or all False?

前端 未结 7 2110
醉话见心
醉话见心 2020-12-07 09:24

In Python, how do I create a numpy array of arbitrary shape filled with all True or all False?

7条回答
  •  我在风中等你
    2020-12-07 09:46

    If it doesn't have to be writeable you can create such an array with np.broadcast_to:

    >>> import numpy as np
    >>> np.broadcast_to(True, (2, 5))
    array([[ True,  True,  True,  True,  True],
           [ True,  True,  True,  True,  True]], dtype=bool)
    

    If you need it writable you can also create an empty array and fill it yourself:

    >>> arr = np.empty((2, 5), dtype=bool)
    >>> arr.fill(1)
    >>> arr
    array([[ True,  True,  True,  True,  True],
           [ True,  True,  True,  True,  True]], dtype=bool)
    

    These approaches are only alternative suggestions. In general you should stick with np.full, np.zeros or np.ones like the other answers suggest.

提交回复
热议问题