Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace values in array using mask of different dimension

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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]]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading