numpy.where#

numpy.where(condition,[x,y,]/)#

Return elements chosen fromx ory depending oncondition.

Note

When onlycondition is provided, this function is a shorthand fornp.asarray(condition).nonzero(). Usingnonzero directly should bepreferred, as it behaves correctly for subclasses. The rest of thisdocumentation covers only the case where all three arguments areprovided.

Parameters:
conditionarray_like, bool

Where True, yieldx, otherwise yieldy.

x, yarray_like

Values from which to choose.x,y andcondition need to bebroadcastable to some shape.

Returns:
outndarray

An array with elements fromx wherecondition is True, and elementsfromy elsewhere.

See also

choose
nonzero

The function that is called when x and y are omitted

Notes

If all the arrays are 1-D,where is equivalent to:

[xvifcelseyvforc,xv,yvinzip(condition,x,y)]

Examples

>>>importnumpyasnp>>>a=np.arange(10)>>>aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>>np.where(a<5,a,10*a)array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

This can be used on multidimensional arrays too:

>>>np.where([[True,False],[True,True]],...[[1,2],[3,4]],...[[9,8],[7,6]])array([[1, 8],       [3, 4]])

The shapes of x, y, and the condition are broadcast together:

>>>x,y=np.ogrid[:3,:4]>>>np.where(x<y,x,10+y)# both x and 10+y are broadcastarray([[10,  0,  0,  0],       [10, 11,  1,  1],       [10, 11, 12,  2]])
>>>a=np.array([[0,1,2],...[0,2,4],...[0,3,6]])>>>np.where(a<4,a,-1)# -1 is broadcastarray([[ 0,  1,  2],       [ 0,  2, -1],       [ 0,  3, -1]])
On this page