A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.
all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.
If we have a Numpy array with boolean, True or False data, we can use np. all() to check if all of the elements are True .
Boolean arrays A boolean array is a numpy array with boolean (True/False) values. Such array can be obtained by applying a logical operator to another numpy array: import numpy as np a = np. reshape(np.
numpy already allows the creation of arrays of all ones or all zeros very easily:
e.g. numpy.ones((2, 2))
or numpy.zeros((2, 2))
Since True
and False
are represented in Python as 1
and 0
, respectively, we have only to specify this array should be boolean using the optional dtype
parameter and we are done.
numpy.ones((2, 2), dtype=bool)
returns:
array([[ True, True],
[ True, True]], dtype=bool)
UPDATE: 30 October 2013
Since numpy version 1.8, we can use full
to achieve the same result with syntax that more clearly shows our intent (as fmonegaglia points out):
numpy.full((2, 2), True, dtype=bool)
UPDATE: 16 January 2017
Since at least numpy version 1.12, full
automatically casts results to the dtype
of the second parameter, so we can just write:
numpy.full((2, 2), True)
numpy.full((2,2), True, dtype=bool)
ones
and zeros
, which create arrays full of ones and zeros respectively, take an optional dtype
parameter:
>>> numpy.ones((2, 2), dtype=bool)
array([[ True, True],
[ True, True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
[False, False]], dtype=bool)
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.
benchmark for Michael Currie's answer
import perfplot
bench_x = perfplot.bench(
n_range= range(1, 200),
setup = lambda n: (n, n),
kernels= [
lambda shape: np.ones(shape, dtype= bool),
lambda shape: np.full(shape, True)
],
labels = ['ones', 'full']
)
bench_x.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With