Categories
Python Answers

How to test whether a Python NumPy array contains a given row?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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