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

Numpy chained index force to be view rather than copy

Basically I want this chained slicing to overwrite the value (show the first element as a 2 instead of 1)

tst = np.array([1,2,3,4])
msk1 = [True, False, True, False]
msk2 = [True, False]
tst[msk1][msk2] = 2

tst
> array([1, 2, 3, 4])

>Solution :

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

This issue is that tst[msk1] is a copy by slicing, and not a view.

You can check it using tst[msk1].base that returns nothing (it would return the original array if a view). So when you further slice and modify tst[msk1][mask2] = 2, you actually modify the in memory copy, not tst.

To my knowledge, you cannot force a view with fancy indexing, so what you want is not directly achievable.

One workaround might be to get the indices of the first mask, and then to slice them with the second mask:

idx = np.where(msk1)[0][msk2]
tst[idx] = 2

# print(tst)
# [2 2 3 4]
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