userE
userE

Reputation: 249

Generate boolean mask from numpy.where output

Is it possible to generate a boolean mask from the output of numpy.where()?

Specifically, I would like to use the output of where to select values while retaining the shape of the array because further processing needs to be done row-wise, however, np.where directly flattens the array without retaining the dimensions:

import numpy as np
A = np.random.random((10, 10))
A[np.where(A > 0.9)]

Out[76]: 
array([0.98981282, 0.9128424 , 0.92600831, 0.98639861, 0.97051929,
       0.90718864, 0.95667512])

But what I would like to get is either a (10,10) boolean mask, or the actual values from A, but then in a way that the dimension are identifiable.

My current work around looks like this, but I am not sure whether there isn't a better, more direct, way of doing it.

A = np.random.random((10, 10))
B = np.nan * np.zeros_like(A)
C = np.where(A > 0.9, A, B)

where I can do the processing for each row separately.

Upvotes: 1

Views: 191

Answers (1)

DYZ
DYZ

Reputation: 57033

What should be in the positions where A<=0.9? Try A * (A > 0.9).

Upvotes: 2

Related Questions