Combine by-integer and by-boolean numpy slicing

Question:

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.

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.

Asked By: orange

||

Answers:

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]

This method generalizes to all logical operators (e.g. &, |, …).


A more memory-efficient method is to apply the same indexing operation i to b:

output = x[i][b[i]]

# For the example in the question,
# x[i] == [6.6, 8.8]
# b[i] == [True, False]
Answered By: Mateen Ulhaq
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.