Check if any value in Numpy Array is negative in Python

This tutorial will discuss about unique ways to check if any value in numpy array is negative in Python.

Table Of Contents

Method 1: Using numpy.any()

The numpy module provides a function numpy.any(). It accepts a boolean sequence as an argument and returns True, if all the elements in this sequence evaluates to True. We can use this function to check if a numpy array contains any negative value.

Apply the < operator on a numpy array, to check if array contains any value less than zero or not. It will return a boolean array, and each True value in this boolean array represent that the corresponding value in the original numpy array is less than zero.

Now pass this boolean array to the numpy.any() method, and it will return True if there is any negative value in numpy array. Like this

np.any(arr < 0)

If this returns True, then it means that the numpy array has at least one negative value.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
arr = np.array([34, 22, 56, -89, 16])

# Check if numpy array has any negative value
if np.any(arr < 0):
    print("The NumPy Array has at least one negative value")
else:
    print("The NumPy Array does not have any negative values")

Output

The NumPy Array has at least one negative value

Method 1: Using any() function

Iterate over all the elements of NumPy array using a for-loop inside a generator expression. For each element, check if it is less than zero or not. It will give us a boolean sequence, and each True value in this sequence represents that the corresponding value in the original NumPy array is less than zero. Pass this boolean sequence to the any() function of Python. It will return true if the boolean sequence has any True value.

Let’s see the complete example,

import numpy as np

# Create a NumPy Array
arr = np.array([34, 22, 56, -89, 16])

# Check if numpy array has any negative value
if any(x < 0 for x in arr):
    print("The NumPy Array has at least one negative value")
else:
    print("The NumPy Array does not have any negative values")

Output

The NumPy Array has at least one negative value

Summary

We learned about two ways to check if a NumPy Array contains a negative value in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top