5

So i have two arrays, they have the same dimension but different lenght.

Arr1 = np.array([[Ind1],[Ind2],[Ind3]])

Arr2 = np.array([[Ind7],[Ind3],[Ind3],[Ind4]])

I need to get the position and value of the elements that have the same position and are equal in both arrays.

In the example case the expected answer will be:

Position = 2

Value = Ind3

I'm using python with the numpy module.

2
  • pad the smaller array to be as long as the longer array, then substract one from the other and look with np.where((Arr1-Arr2)==0). Commented Sep 4, 2017 at 18:34
  • Will there only ever be one match? Do you want all matches, or just the first match? Commented Sep 4, 2017 at 18:37

4 Answers 4

5

With NumPy arrays, you might want to work in a vectorized manner for performance and also to make use of array-slicing. With that in mind, here's one approach for input arrays a and b -

n = min(len(a), len(b))
out_idx = np.flatnonzero(a[:n] == b[:n])
out_val = a[out_idx] # or b[out_idx] both work

This takes care of multiple matches.

Sample run -

In [224]: a = np.array([3, 8, 9, 2, 1, 7])

In [225]: b = np.array([1, 2, 9, 7, 5, 7, 0, 4])

In [226]: n = min(len(a), len(b))
     ...: out_idx = np.flatnonzero(a[:n] == b[:n])
     ...: out_val = a[out_idx]
     ...: 

In [227]: out_idx
Out[227]: array([2, 5])

In [228]: out_val
Out[228]: array([9, 7])

For a list of tuples as output for indices and their values -

In [229]: zip(out_idx, out_val)
Out[229]: [(2, 9), (5, 7)]

For a pretty dictionary output of indices and corresponding values -

In [230]: {i:j for i,j in zip(out_idx, out_val)}
Out[230]: {2: 9, 5: 7}
Sign up to request clarification or add additional context in comments.

Comments

2

You could also use intersect1d to get the same values:

np.intersect1d(a,b)

Comments

1

Assuming the lists are called lst_1 and lst_2, you could do something like

for i in range(min(len(lst_1), len(lst_2)):
    if lst_1[i] == lst_2[i]:
        return lst_1[i], i

This will return a tuple containing the common element and its index. Note that if there are multiple matches, the first one will be returned; if no matches exist, None is returned.

1 Comment

i will modify this to return a list of elements and positions
0

I had the same issue when I was trying to compare two arrays of different sizes. I simply converted those to list and now it doesn't throw any warning/error.

The code I used to convert arrays to list is -

import numpy as np
np.array([[1,2,3],[4,5,6]]).tolist()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.