I have two numpy arrays, A and B. A conatains unique values and B is a sub-array of A. Now I am looking for a way to get the index of B's values within A.
For example:
A = np.array([1,2,3,4,5,6,7,8,9,10]) B = np.array([1,7,10]) # I need a function fun() that: fun(A,B) >> 0,6,9
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.
Now if there is a comma and a colon, python will pass a tuple which contains a slice. in your example: foo[:, 1] # passes the tuple `(slice(None, None, None), 1)` What the object ( foo ) does with the input is entirely up to the object. Follow this answer to receive notifications.
k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.
The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.
You can use np.in1d
with np.nonzero
-
np.nonzero(np.in1d(A,B))[0]
You can also use np.searchsorted
, if you care about maintaining the order -
np.searchsorted(A,B)
For a generic case, when A
& B
are unsorted arrays, you can bring in the sorter
option in np.searchsorted
, like so -
sort_idx = A.argsort() out = sort_idx[np.searchsorted(A,B,sorter = sort_idx)]
I would add in my favorite broadcasting
too in the mix to solve a generic case -
np.nonzero(B[:,None] == A)[1]
Sample run -
In [125]: A Out[125]: array([ 7, 5, 1, 6, 10, 9, 8]) In [126]: B Out[126]: array([ 1, 10, 7]) In [127]: sort_idx = A.argsort() In [128]: sort_idx[np.searchsorted(A,B,sorter = sort_idx)] Out[128]: array([2, 4, 0]) In [129]: np.nonzero(B[:,None] == A)[1] Out[129]: array([2, 4, 0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With