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

Advanced indexing/subsetting in numpy?

How using numpy, given a larger a and a smaller boolean array b

a = np.array([False, True, True, False, True])
b = np.array([False, True, False])

obtain the result c?

c = np.array([False, False, True, False, False])

That is to do the boolean and between b the part of a which is True to obtain the array c of the same shape as a? The number of elements that are True in the array a and the length of the array b does match.

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

>Solution :

How about this:

c = np.copy(a)
c[a] = b

First, c is created by copying a. Now, a, which is a boolean array, is used to select the elements of c where a is True.

Since a boolean and between some value and True is the value itself, boolean and between the array b and those elements of a that are True is simply the array b itself.

Finally, because the number of True elements of a is the same as the length of b, the assignment c[a] = b is possible.

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