2
import numpy as np

A and B arrays are in good order.

A = np.array(['a','b','c','d','e'])
B = np.array([5,7,3,9,11])

C = np.array(['a','b','k','j','p','x'])

For each element of array C, if that element is in A, get value from B of the same position as B. If not in A, write np.nan.

The expected result would be:

result = np.array([5,7,na,na,na,na])

How is the easeist way of doing it in numPy?

1 Answer 1

4

You could use np.in1d(C, A) to determine if C is in A.

In [110]: np.in1d(C, A)
Out[115]: array([ True,  True, False, False, False], dtype=bool)

Then use np.where to select the desired values from B or np.nan:

In [116]: np.where(np.in1d(C, A), B, np.nan)
Out[116]: array([  5.,   7.,  nan,  nan,  nan])

np.where(cond, B, np.nan) returns an array of the same shape as the boolean array cond. The returned array takes a value from B if the corresponding value in cond is True, and is np.nan otherwise.


If len(C) > len(B), and if you would like the final array to contain NaNs for the last len(C)-len(B) values, then you could use:

N = len(B)
result = np.full(len(C), np.nan)
result[:N] = np.where(np.in1d(C[:N], A), B, np.nan)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, accepted !, Unfortunately ValueError: operands could not be broadcast together with shapes (18,) (19,) () if A and C are NOT in same shape. How to do in this case?
That could happen if B is shorter than C. What do you want to happen if an element in C is in A but there is no corresponding value in B?
Both A and B are same shapes.
If an eleemnt in C is present in A, get corresponding value from B. If not in A, get np.nan
If C = np.array(['a','b','k','j','p','a']) then what should the result be?

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.