Search code examples
pythonarraysnumpyindexing

Assigning to a double-indexed numpy array


I know that when assigning to a double indexed-array gives bad results because you're assigning to a view rather then to an array directly, but I cannot figure out how to properly assign to double-indexed array:

import numpy as np
foo = np.array([1, 2, 3, 4, 5])
bar = np.array([False, True, True, True, False])
foo[bar][1:2] = np.array([30, 40])
foo #array([1, 2, 30, 40, 5])

Is there a way to assign a value(array) to doubly-indexed array?


Solution

  • Assuming you want to index using both a boolean array and a slice of the True values in this array, you would need to compute another boolean array that summarizes those conditions.

    Here is a possible approach based on the indices of the boolean array:

    idx = np.arange(len(bar))
    foo[idx[bar][1:3]] = np.array([30, 40])
    

    output: array([ 1, 2, 30, 40, 5])