1

I have two 2d numpy arrays and want to find where one array is occuring in another one:

big_array = np.array([[1., 2., 1.2], [5., 3., 0.12], [-1., 14., 0.], [-9., 0., 13.]])
small_array= np.array([[5., 3., 0.12], [-9., 0., 13.]])

Then I want to get the indices of the rows of big_array which are the same as any rows of small_array. I want to do somthing like np.in1d for 2d arrays. I mean I want to have:

result= [1, 3]

I already tried the following code but it was not successful:

result=[([any(i == big_array ) for i in small_array])]

In advance, I do appreciate any help.

Ali_d
  • 1,089
  • 9
  • 24

1 Answers1

1

What you want is:

sum([row in small_array for row in big_array])

Example:

import numpy as np
big_array = np.array([[1., 2., 1.2], [5., 3., 0.12], [-1., 14., 0.], [-9., 0., 13.]])
small_array= np.array([[5., 3., 0.12], [-1., 14., 0.]])

result = sum([row in small_array for row in big_array])
print(result)

2


Edit (after clarifications):

A pythonic solution:

[i for i, brow in enumerate(big_array) for srow in small_array if all(srow == brow)]

Example:

big_array = np.array([[1., 2., 1.2], [5., 3., 0.12], [-1., 14., 0.], [-9., 0., 13.]])
small_array= np.array([[5., 3., 0.12], [-1., 14., 0.]])

result = [i for i, brow in enumerate(big_array) for srow in small_array if all(srow == brow)]

print(result)

[1, 2]

Note: you could probably do something better with np.where, if you have huge arrays you should look it up

Djib2011
  • 6,874
  • 5
  • 36
  • 41
  • Dear @Djib2011, Thanks for your help. Your solution is giving me the total number of rows which are the same, but I want to find the indices of this rows in the `big_array`. I want to do somthing like `np.in1d` for 2d arrays. – Ali_d Nov 25 '20 at 09:00
  • @Ali_d I misinterpreted your original question. Now after clarifications, I updated my answer. – Djib2011 Nov 25 '20 at 09:39