Allocate array with values and indices from other arrays

Question:

I have 2 arrays, one with values and the other with indices. Can I populate another array (with different dimensions) using these two in numpy?

vals = [[0.7, 0.7, 0.2, 0.1], 
        [0.3, 0.2, 0.1, 0.1]]
indices = [[2, 5, 6, 8], 
           [0, 1, 2, 7]]
required_array = [[0, 0, 0.7, 0, 0, 0.7, 0.2, 0, 0.1], 
                  [0.3, 0.2, 0.1, 0, 0, 0, 0, 0.1, 0]]          

Note that the values for the indexes that aren’t present in the indices array (like 0,1,3,…) are filled with 0.

Asked By: helloworld

||

Answers:

First allocate an all zero array, then set the value:

>>> ar = np.zeros(np.max(indices) + 1)
>>> ar[indices] = vals
>>> ar
array([0. , 0. , 0.7, 0. , 0. , 0.7, 0.2, 0. , 0.1])

2d example:

>>> ar = np.zeros((len(indices), np.max(indices) + 1))
>>> ar[np.arange(len(indices))[:, None], indices] = vals
>>> ar
array([[0. , 0. , 0.7, 0. , 0. , 0.7, 0.2, 0. , 0.1],
       [0.3, 0.2, 0.1, 0. , 0. , 0. , 0. , 0.1, 0. ]])
Answered By: Mechanic Pig
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.