Home > Enterprise >  Allocate array with values and indices from other arrays
Allocate array with values and indices from other arrays

Time:10-06

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.

CodePudding user response:

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. ]])
  • Related