Thursday, October 21, 2021

Ben Cook: NumPy Any: Understanding np.any()

The np.any() function tests whether any element in a NumPy array evaluates to true:

np.any(np.array([[1, 0], [0, 0]]))

# Expected result
# True

The input can have any shape and the data type does not have to be boolean (as long as it’s truthy). If none of the elements evaluate to true, the function returns false:

np.any(np.array([[0, 0], [0, 0]]))

# Expected result
# False

Passing in a value for the axis argument makes np.any() a reducing operation. Say we want to know which rows in a matrix have any truthy elements. We can do that by passing in axis=-1:

np.any(np.zeros((2, 3)), axis=-1)

# Expected result
# array([False, False])

There are two rows and for each of them, none of the elements evaluate to true. The -1 value here is shorthand for “the last axis”.

Easy enough! NumPy also has a function called np.all() which has the same API as np.any() but returns true when all of the elements evaluate to true.

The post NumPy Any: Understanding np.any() appeared first on Sparrow Computing.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...