Home > OS >  Replace values in array using mask of different dimension
Replace values in array using mask of different dimension

Time:08-27

I read this answer and wondered if this can be used to replace nested arrays.

So I tried:

import numpy as np

frm = [[[1,2], [2,3]], [[3,4], [4,5]], [[5,6], [6,7]]]
mask = [[False, True], [False, True], [True, False]]
repl = [0,0]
# convert frm to a numpy array:
frm = np.array(frm)
# create a copy of frm so you don't modify original array:
to = frm.copy()

# mask to, and insert your replacement values:
to[mask] = repl

print(to)

However I get the error IndexError: boolean index did not match indexed array along dimension 0; dimension is 3 but corresponding boolean dimension is 2

My goal here is to replace a nested array with another array. E.g. I want this value [2,3] in the first column to be replaced by this [0,0]

CodePudding user response:

Try this:

to[np.newaxis, mask] = repl

or you convert the mask and the values to be replaced to an array. Then it is also working.

frm = [[[1,2], [2,3]], [[3,4], [4,5]], [[5,6], [6,7]]]
mask = np.array([[False, True], [False, True], [True, False]])
repl = np.array([0,0])
# convert frm to a numpy array:
frm = np.array(frm)
# create a copy of frm so you don't modify original array:
to = frm.copy()

# mask to, and insert your replacement values:
to[mask] = repl

print(to)

Output:

[[[1 2]
  [0 0]]

 [[3 4]
  [0 0]]

 [[0 0]
  [6 7]]]
  • Related