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

Combine by-integer and by-boolean numpy slicing

I’m looking for a way to combine two index arrays b and i (one of type boolean, one of type integer) to slice another array x.

x = np.array([5.5, 6.6, 3.3, 7.7, 8.8])
i = np.array([1, 4])
b = np.array([True, True, False, False, False])

The resulting array should be x == [6.6] because it’s indexed by i (i[0]) and by the value in b[1].

In other words, I’m looking for a way to express x[i & b] with i being an integer array. I know how to convert boolean index arrays to integer index arrays (np.where(b)), but that would merely shift the problem to combining two integer index arrays, which I also don’t have a solution for.

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

Obviously subsequent slicing doesn’t work (i.e. x[i][b] or vice versa), because the dimensionality changes after each separate slicing.

Any help would be appreciated.

>Solution :

One O(n) method is to convert the index array i to a boolean array and then take the &:

b_i = np.zeros_like(b)
b_i[i] = True

output = x[b_i & b]
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