All() And Any() Functions On Numpy.ndarray

Overview:

  • Given an n-dimensional matrix, its contents can be checked whether all of its elements evaluate to True or any of its elements evaluate to True.

 

  • The all() method of numpy.ndarray can be used to check whether all of the elements of an ndarray object evaluate to True.

 

  • The any() method of numpy.ndarray  can be used to find whether any of the elements of an ndarray object evaluate to True.

 

  • These tests can be performed considering the n-dimensional array as a flat array or over a specific axis of the array.

 

  • When the axis is not specified these operations are performed on the whole array and when the axis is specified these operations are performed on the given axis.

 

  • While all() method performs a logical AND operation on the ndarray elements or the elements along the given axis of the ndarray, the any() method performs a logical OR operation.

 

Example: numpy.ndarray.all()

import numpy as np

 

# Create a 3 dimensional array

Array_3d = np.arange(9).reshape(3,3)

 

print("2 dimensional input array:")

print(Array_3d)

 

print("Return values from all():")

print("-------------------------")

print("When no axis is specified:")

print(Array_3d.all())

print("When no axis is specified and keepdims = True:")

print(Array_3d.all(keepdims=True))

print("When axis=0")

print(Array_3d.all(axis=0))

print("When axis=0,  keepdims = True:")

print(Array_3d.all(axis=0, keepdims=True))

Output:

2 dimensional input array:

[[0 1 2]

 [3 4 5]

 [6 7 8]]

Return values from all():

-------------------------

When no axis is specified:

False

When no axis is specified and keepdims = True:

[[False]]

When axis=0

[False  True  True]

When axis=0,  keepdims = True:

[[False  True  True]]

 

Example: numpy.ndarray.any()

import numpy as np

 

# Create a 3 dimensional array

Array_3d = np.arange(9).reshape(3,3)

 

print("2 dimensional input array:")

print(Array_3d)

 

print("Return values from any():")

print("-------------------------")

print("When no axis is specified:")

print(Array_3d.any())

print("When no axis is specified and keepdims = True:")

print(Array_3d.any(keepdims=True))

print("When axis=0")

print(Array_3d.any(axis=0))

print("When axis=0,  keepdims = True:")

print(Array_3d.any(axis=0, keepdims=True))

Output:

2 dimensional input array:

[[0 1 2]

 [3 4 5]

 [6 7 8]]

Return values from any():

-------------------------

When no axis is specified:

True

When no axis is specified and keepdims = True:

[[ True]]

When axis=0

[ True  True  True]

When axis=0,  keepdims = True:

[[ True  True  True]]

 

 


Copyright 2020 © pythontic.com