1

I have a smaller array as:

A = np.array([2011, 2014, 2015, 2016, 2017])
Aval = np.array([14, 10, 35, 40, 45])

I have another array:

A2 = np.array([2013, 2014, 2015, 2014, 2015, 2016, 2016, 2016, 2017])

I want to create A2val such that:

Arval = np.array([10, 35, 10, 35, 40, 40, 40, 45])

so, I am trying to use the values in array A to map to elements of A2 and generate an extended version of A2val

Please note 2011 is present in A, 2013 is in A2 but not in A2 and A respectively. I can use the following suggested in another thread:

Aval[np.searchsorted(A,A2)]

But it doesn't produce the answer I am looking for.

2 Answers 2

4

Here is one way:

>>> Aval[np.searchsorted(A, A2[np.nonzero(np.in1d(A2, A))[0]])]
array([10, 35, 10, 35, 40, 40, 40, 45])

Note that for getting the expected indices in default order the second array that you pass to searchsorted() should be contain the common items with first array.

Sign up to request clarification or add additional context in comments.

Comments

1

You can construct a dictionary from A and Aval and then loop through A2 and find out the corresponding values:

dic = dict(zip(A, Aval))
[dic.get(a) for a in A2 if dic.get(a) != None]
# [10, 35, 10, 35, 40, 40, 40, 45]

Comments

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.