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}
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.
您还可以使用 intersect1d 来获得相同的值:
np.intersect1d(a,b)
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.