NumPy ndarray.all()
The numpy.ndarray.all()
method checks whether all elements in a NumPy array evaluate to True
.
It can operate across the entire array or along a specified axis.
Syntax
ndarray.all(axis=None, out=None, keepdims=False, *, where=True)
Parameters
Parameter | Type | Description |
---|---|---|
axis | None, int, or tuple of ints, optional | Axis or axes along which a logical AND operation is performed. If None , it checks the entire array. |
out | ndarray, optional | Alternative output array for storing the result. Must have the same shape as expected output. |
keepdims | bool, optional | If True , the reduced dimensions are kept as size one, allowing proper broadcasting. |
where | array_like of bool, optional | Specifies elements to include in the check for all True values. |
Return Value
Returns a boolean value if axis=None
, or an array of boolean values if an axis is specified.
The result is True
if all elements (or elements along the specified axis) evaluate to True
, otherwise False
.
Examples
1. Checking if All Elements Are True in ndarray
In this example, we create a 2×2 boolean array and check if all its elements are True
.
import numpy as np
arr = np.array([[True, False],
[True, True]])
result = arr.all()
print(result)
Output:
False
Since there is at least one False
value in the array, the all()
method returns False
.
2. Using the axis
Parameter in ndarray.all()
Here, we check if all elements along a specific axis are True
.
import numpy as np
arr = np.array([[True, False],
[True, True]])
result_axis0 = arr.all(axis=0)
print(result_axis0)
result_axis1 = arr.all(axis=1)
print(result_axis1)
Output:
[ True False]
[False True]
For axis=0
(columns), it checks if all elements in each column are True
. The first column has all True
values, but the second column has a False
, so the result is [True, False]
.
For axis=1
(rows), it checks if all elements in each row are True
. The first row has a False
, so it returns False
, but the second row is all True
, so it returns True
.
3. Keeping Dimensions with keepdims=True
in ndarray.all()
In this example, we use keepdims=True
to retain the reduced axis as a dimension of size one.
import numpy as np
arr = np.array([[True, True],
[True, True]])
result = arr.all(axis=1, keepdims=True)
print(result)
Output:
[[ True]
[ True]]
Even though the result is True
for both rows, keeping dimensions ensures that the output retains the original shape, making it useful for broadcasting operations.
4. Using the where
Parameter in ndarray.all()
The where
parameter allows checking only specific elements for True
values.
import numpy as np
arr = np.array([True, False, True])
mask = np.array([True, False, True])
result = arr.all(where=mask)
print(result)
Output:
True
Here, only the elements where mask
is True
are considered. Since the first and last elements are both True
, the result is True
, even though the middle element is False
because it is ignored due to the mask.