numpy.where() i Python

De numpy.where() funktion returnerar index för element i en inmatningsmatris där det givna villkoret är uppfyllt.

Syntax : numpy.where(villkor[, x, y])
Parametrar:
skick : När sant, ge x, annars ger y.
x, y: Värden att välja mellan. x, y och condition måste kunna sändas till någon form.

Returnerar:
ut: [ndarray eller tuppel av ndarrays] Om både x och y är specificerade innehåller utmatrisen element av x där villkoret är True och element från y någon annanstans.

Om endast villkoret ges, returnera tuple condition.nonzero(), indexen där villkoret är True.

Kod #1:




# Python program explaining> # where() function> > import> numpy as np> > np.where([[> True> ,> False> ], [> True> ,> True> ]],> > [[> 1> ,> 2> ], [> 3> ,> 4> ]], [[> 5> ,> 6> ], [> 7> ,> 8> ]])>

Utgång:

array([[1, 6], [3, 4]]) 

Kod #2:




# Python program explaining> # where() function> > import> numpy as np> > # a is an array of integers.> a> => np.array([[> 1> ,> 2> ,> 3> ], [> 4> ,> 5> ,> 6> ]])> > print> (a)> > print> (> 'Indices of elements <4'> )> > b> => np.where(a <> 4> )> print> (b)> > print> (> 'Elements which are <4'> )> print> (a[b])>

Utgång:

[[1 2 3] [4 5 6]] Indices of elements  <4 (array([0, 0, 0], dtype=int64), array([0, 1, 2], dtype=int64)) Elements which are  <4 array([1, 2, 3])