If you have a numpy array and you want to check if any row contains negative values, there are several ways to do so.
Table of contents
Create synthetic data
First, let's generate artificial data and use it to create a numpy array.
import numpy as np
np.random.seed(42)
data = np.random.uniform(low=-9.0, high=100.0, size=(10,4))
print(data)
Output
[[31.82487295 94.6278594 70.78733966 56.25377478]
[ 8.00603181 8.00340272 -2.66888627 85.41319989]
[56.52153628 68.17991098 -6.75629012 96.72017389]
[81.73624785 14.14496306 10.81892143 10.99109157]
[24.16240448 48.19845105 38.08200703 22.74397628]
[57.69196552 6.20483081 22.84376669 30.93344092]
[40.71162828 76.58417979 12.76444226 47.05155379]
[55.57318801 -3.93690501 57.22238886 9.58712948]
[-1.90937636 94.42852356 96.25389161 79.11531094]
[24.20290084 1.64626043 65.58139989 38.97662182]]
Using any()
A simple approach is to use the numpy.any() function, which returns true if at least one element of an array is non-zero. By giving it the argument of axis=1, this can be used to check if any row in a two-dimensional array contains negative values. So for example, if you have an array called “data”, you would write the following code:
np.any(data < 0, axis=1)
This will return a boolean array indicating which rows have a negative value in at least one of their elements.
array([False, True, True, False, False, False, False, True, True,
False])
Using where()
You can also use the numpy.where() function to get the indices of the rows that contain negative values, by writing:
np.where(data < 0)
This will return a tuple containing two arrays, each giving you the row and column indices of the negative values. Knowing these indices, you can then easily access the elements in question.
(array([1, 2, 7, 8]), array([2, 2, 1, 0]))
References
Links | Site |
---|---|
numpy.any | numpy.org |
numpy.where | numpy.org |