Sometimes, we want to test whether a Python NumPy array contains a given row.
In this article, we’ll look at how to test whether a Python NumPy array contains a given row.
How to test whether a Python NumPy array contains a given row?
To test whether a Python NumPy array contains a given row, we can convert the NumPy array to a list and then use the in
operator to check whether the list is in the nested list.
For instance, we write:
import numpy as np
a = np.array([[1, 2], [10, 20], [100, 200]])
l = a.tolist()
print([1, 2] in l)
print([1, 200] in l)
We can np.array
with a nested list to create an array.
Then we call a.tolist
to convert the NumPy array back to a list.
Next, we use the in
operator to check whether [1, 2]
and [1, 200]
is in l
.
Therefore, print
should print:
True
False
since [1, 2]
is in l
and [1, 200]
isn’t.
Conclusion
To test whether a Python NumPy array contains a given row, we can convert the NumPy array to a list and then use the in
operator to check whether the list is in the nested list.