Home > Back-end >  Numpy array value change via two index sets
Numpy array value change via two index sets

Time:12-16

I am trying to achieve the following:

    # Before
    raw = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

    # Set values to 10
    indice_set1 = np.array([0, 2, 4])
    indice_set2 = np.array([0, 1])
    raw[indice_set1][indice_set2] = 10

    # Result
    print(raw)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

But the raw values remain exactly the same.

Expecting this:

    # After
    raw = np.array([10, 1, 10, 3, 4, 5, 6, 7, 8, 9])

CodePudding user response:

After doing raw[indice_set1] you get a new array, which is the one you modify with the second slicing, not raw.

Instead, slice the slicer:

raw[indice_set1[indice_set2]] = 10

Modified raw:

array([10,  1, 10,  3,  4,  5,  6,  7,  8,  9])
  • Related