0

I was wondering if there's any built-in method to find arrays of a ndarray that are contained into another ndarray. i.e.

arr1 = [[1,2], [2,9], [3,7], [5,11], [32,5], [11,4], [89,3], [37,5]]

and

arr2 = [[12,44], [2,9], [125,3], [37,5]]

I would like to know if there's any built-in method to identify that [2,9] and [37,5] are the only arrays of arr2 contained into arr1. Or to identify their indexes.

Kromag
  • 47
  • 1
  • 6

3 Answers3

0

You could use sets and tuples, to do this, using:

arr1 = [[1,2], [2,9], [3,7], [5,11], [32,5], [11,4], [89,3], [37,5]]
arr2 = [[12,44], [2,9], [125,3], [37,5]]

set1 = {tuple(i) for i in arr1}
set2 = {tuple(i) for i in arr2}

arr3 = [list(i) for i in set1 & set2]

But it would be much simpler just to use a list comprehension

arr3 = [i for i in arr1 if i in arr2]
dangee1705
  • 3,445
  • 1
  • 21
  • 40
0

If you use sets:

a = [1,2,3,4,"B"]
b = [2, "B", 5]
sa = set(a)
sb = set(b)
c = list(sa.intersection(sb))

c will be:

[2, "B"]
Artemis
  • 2,553
  • 7
  • 21
  • 36
0

One way is to use intersection of rows of the 2 lists, after mapping each row to tuple.

The reason why conversion to tuple is necessary is because tuples are immutable and hashable. Therefore, they can be included in a set, while lists cannot.

arr1 = [[1,2], [2,9], [3,7], [5,11], [32,5], [11,4], [89,3], [37,5]]
arr2 = [[12,44], [2,9], [125,3], [37,5]]

res = set(map(tuple, arr1)) & set(map(tuple, arr2))

# {(2, 9), (37, 5)}

If required, convert the result back to lists:

res2 = list(map(list, res))

# [[37, 5], [2, 9]]

Alternative, possibly more efficient, solutions if numpy arrays are viable:

  1. Get intersecting rows across two 2D numpy arrays
  2. Find arrays of ndarray that are in another ndarray - Python
jpp
  • 159,742
  • 34
  • 281
  • 339