Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

python - Masking numpy arrays to select specific rows, based on another boolean array

Suppose that I have an array like this:

my_arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

or a 2D array like:

my_arr = np.array([[1, 1, 11], [2, 1, 0], [3, 3, -1], ..., [10, 9, 0]])

And I define an array like

mask_arr = ([1, 1, 0, 0, 1, 0, 1, 1, 0, 1])

What I want to do from the mask array is to obtain a new array which is consisted of rows, wherein the mask_arr of their index, the element is equal to "1".

For example, the result of the first array would be like:

[1, 2, 0, 0, 5, 0, 7, 8, , 10]

I tried

my_arr[my_mask]

But it didn't work. Is there any solution without wanting to write a for loop to do that?

Thank you in advance

question from:https://stackoverflow.com/questions/65948120/masking-numpy-arrays-to-select-specific-rows-based-on-another-boolean-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your mask_arr looks like integer type, and when you slice with an integer array, the array is treated as indexes. So

my_arr[[0,1,1]]

would give you [row0,row1,row1]. As you mentioned, you want to treat mask_arr as boolean, then you can convert it to boolean:

my_arr[mask_arr.astype('bool')]

will extract the rows corresponding to the 1 in mask_arr.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...