How to check if elements of an array evaluate to true in Python

Overview

The ma.all() function in Python is used to check if all the elements of an array along a given axis evaluate to True.

Syntax

ma.all(a, axis=None, out=None, keepdims=<no value>)

Required parameter value

The ma.all() function takes a mandatory parameter, a, which represents the input array or objects that can be converted to an array.

Optional parameter values

The ma.all() function takes the following optional parameter values:

  • axis: This represents the axis or axes along which a logical AND reduction operation is performed. The default value is (axis = None) and when negative, it counts from the last to the first axis.
  • out: This represents an alternate output array in which to place the result. It must have the same shape as the expected output array.
  • keepdims: If this is set to True, axes that are reduced are left in the result as dimensions with size one.

Return value

The ma.all() function returns a boolean value or array.

Example

import numpy as np
# creating an array
my_array = np.ma.arange(6) + 1
# calling the ma.all() function
new_array = np.all(my_array)
# printing the array
print(new_array)

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array variable, my_array.
  • Line 7: We implement the ma.all() function on the array my_array. We assign the result to a new variable, new_array.
  • Line 10: We printed the variable new_array.

Free Resources