sunny
sunny

Reputation: 3881

How to index numpy array on subset of array of bools that is smaller than numpy array's dimensions?

My question is inspired by another one: Intersection of 2d and 1d Numpy array I am looking for a succinct solution that does not use in1d

The setup is this. I have a numpy array of bools telling me which values of numpy array A I should set equal to 0, called listed_array. However, I want to ignore the information in the first 3 columns of listed_array and only set A to zero as indicated in the other columns of listed_array.

I know the following is incorrect:

A[listed_array[:, 3:]] = 0

I also know I can pad this subset of listed_array with a call to hstack, and this will yield correct output, but is there something more succinct?

Upvotes: 2

Views: 54

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114781

If I understand the question, this should do it:

A[:, 3:][listed_array[:, 3:]] = 0

which is a concise version of

mask3 = listed_array[:, 3:]
A3 = A[:, 3:]   # This slice is a *view* of A, so changing A3 changes A.
A3[mask3] = 0

Upvotes: 1

Related Questions