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.
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}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments