user1846418
user1846418

Reputation: 69

Replace values by indices of corresponding to another array

I am a newbie in numpy. I have an array A of size [x,] of values and an array B of size [y,] (y > x). I want as result an array C of size [x,] filled with indices of B.

Here is an example of inputs and outputs:

>>> A = [10, 20, 30, 10, 40, 50, 10, 50, 20]
>>> B = [10, 20, 30, 40, 50]
>>> C = #Some operations
>>> C
[0,  1,  2,  0,  3,  4,  0,  4, 1]

I didn't find the way how to do this. Please advice me. Thank you.

Upvotes: 1

Views: 201

Answers (3)

meTchaikovsky
meTchaikovsky

Reputation: 7666

You can try this code

A = np.array([10, 20, 30, 10, 40, 50, 10, 50, 20])
B = np.array([10, 20, 30, 40, 50])

np.argmax(B==A[:,None],axis=1)

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150735

I think you are looking for searchsorted, assuming that B is sorted increasingly:

C = np.searchsorted(B,A)

Output:

array([0, 1, 2, 0, 3, 4, 0, 4, 1])

Update for general situation where B is not sorted. We can do an argsort:

# let's swap 40 and 50 in B
# expect the output to have 3 and 4 swapped
B = [10, 20, 30, 50, 40]

BB = np.sort(B)

C = np.argsort(B)[np.searchsorted(BB,A)]

Output:

array([0, 1, 2, 0, 4, 3, 0, 3, 1], dtype=int64)

You can double check:

(np.array(B)[C] == A).all()
# True

Upvotes: 1

wasif
wasif

Reputation: 15470

For general python lists

A = [10, 20, 30, 10, 40, 50, 10, 50, 20]
B = [10, 20, 30, 40, 50]


C = [A.index(e) for e in A if e in B]

print(C)

Upvotes: 1

Related Questions