pythonnumpyboolean

init 1D numpy array with boolean mask and a smaller array containing nonzero values


Problem

I have valid_data (1D np.array with nonzero values) and mask (boolean 1D np.array), which are not of the same size. The mask contains the wanted positions of the valid_data in a new np.array to create. Can I initialize this new np.array easily, or do I have to calculate it value by value?

Example

>>> mask = np.array([False, True, False, False, False, True, True, False, False, False])
>>> valid_data = np.array([1, 3, 3])
>>> 
>>> wanted_result = np.array([0, 1, 0, 0, 0, 3, 3, 0, 0, 0])
>>> 
>>> my_try = np.where(mask, valid_data, 0)

But I can't use np.where with arrays of different shapes. We can assume that the number of True values in mask matches the number of values in valid_data.


Solution

  • Create an array of zeros using np.zeros with the length of mask, and then assign the values from valid_data where mask is True:

    arr = np.zeros(len(mask), dtype=int)
    arr[mask] = valid_data
    

    Output:

    array([0, 1, 0, 0, 0, 3, 3, 0, 0, 0])