Zanam
Zanam

Reputation: 4807

Numpy using smaller 2D array to map with bigger array with more elements

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.

Upvotes: 1

Views: 583

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

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.

Upvotes: 4

akuiper
akuiper

Reputation: 214927

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]

Upvotes: 1

Related Questions