Categories
Python Answers

How to get intersecting rows across two 2D Python NumPy arrays?

Spread the love

Sometimes, we want to get intersecting rows across two 2D Python NumPy arrays.

In this article, we’ll look at how to get intersecting rows across two 2D Python NumPy arrays.

How to get intersecting rows across two 2D Python NumPy arrays?

To get intersecting rows across two 2D Python NumPy arrays, we can convert the arrays to sets and then use the & operator to get the intersection of both sets.

For instance, we write:

import numpy as np

A = np.array([[1, 4], [2, 5], [3, 6]])
B = np.array([[1, 4], [3, 6], [7, 8]])
aset = set([tuple(x) for x in A])
bset = set([tuple(x) for x in B])
intersection = np.array([x for x in aset & bset])
print(intersection)

We have 2 arrays of lists A and B that we created with np.array.

Then we convert both arrays to sets with set.

And we convert each entry in A and B to tuples with tuple.

Next, we get the common entries from each set with [x for x in aset & bset] and put them in a list.

Finally, we convert the list back to an array with np.array.

Therefore, intersection is:

[[1 4]
 [3 6]]

Conclusion

To get intersecting rows across two 2D Python NumPy arrays, we can convert the arrays to sets and then use the & operator to get the intersection of both sets.

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 *