numpy.where() em Python

O módulo NumPy fornece uma função numpy.where() para selecionar elementos com base em uma condição. Retorna elementos escolhidos de a ou b dependendo da condição.

Por exemplo, se todos os argumentos -> condição, a & b forem passados ​​em numpy.where() então ele retornará elementos selecionados de a & b dependendo dos valores na matriz bool produzida pela condição.

Se apenas a condição for fornecida, esta função será uma abreviação da função np.asarray (condição).nonzero(). Embora diferente de zero deva ser preferido diretamente, pois se comporta corretamente para subclasses.

Sintaxe:

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

Parâmetros:

Estes são os seguintes parâmetros na função numpy.where():

condição: array_like, bool

Se este parâmetro for definido como True, produz x, caso contrário produz y.

x, y: array_like:

Este parâmetro define os valores a serem escolhidos. As condições x, y e precisam ser transmitidas para alguma forma.

Retorna:

Esta função retorna o array com elementos de x onde a condição é True e elementos de y em outro lugar.

Exemplo 1: np.where()

 import numpy as np a=np.arange(12) b=np.where(a<6,a,5*a) b < pre> <p> <strong>In the above code</strong> </p> <ul> <li>We have imported numpy with alias name np.</li> <li>We have created an array &apos;a&apos; using np.arange() function.</li> <li>We have declared the variable &apos;b&apos; and assigned the returned value of np.where() function.</li> <li>We have passed the array &apos;a&apos; in the function.</li> <li>Lastly, we tried to print the value of b.</li> </ul> <p>In the output, the values ranging from 0 to 5 remain the same as per the condition, and the other values have been multiplied with 5.</p> <p> <strong>Output:</strong> </p> <pre> array([ 0, 1, 2, 3, 4, 5, 30, 35, 40, 45, 50, 55]) </pre> <h3>Example 2: For multidimensional array</h3> <pre> import numpy as np a=np.arange(12) b=np.where([[True, False], [True, True]],[[1, 2], [3, 4]],[[9, 8], [7, 6]]) b </pre> <p> <strong>Output:</strong> </p> <pre> array([[1, 8], [3, 4]]) </pre> <h3>Example 3: Broadcasting x, y, and condition</h3> <pre> import numpy as np x, y = np.ogrid[:3, :4] a=np.where(x &gt; y, x, 10 + y) a </pre> <p> <strong>Output:</strong> </p> <pre> array([[10, 11, 12, 13], [ 1, 11, 12, 13], [ 2, 2, 12, 13]]) </pre> <p> <strong>In the above code</strong> </p> <ul> <li>We have imported numpy with alias name np.</li> <li>We have created an array &apos;a&apos; using np.arange() function. </li> <li>We declared the variable &apos;b&apos; and assigned the returned value of np.where() function.</li> <li>We have passed a multidimensional array of boolean as a condition and x and y as an integer arrays.</li> <li>Lastly, we tried to print the value of b.</li> </ul> <p>In the output, the x value has been compared to y value if it satisfied the condition, then it will be printed x value otherwise, it will print y value, which has passed as an argument in the where() function.</p> <h3>Example 4: Broadcasting specific value</h3> <pre> x=np.array([[0,1,2],[0,2,5],[0,4,8]]) y=np.where(x<4,x,-2) y < pre> <p> <strong>Output:</strong> </p> <pre> array([[ 0, 1, 2], [ 0, 2, -2], [ 0, -2, -2]]) </pre> <hr></4,x,-2)></pre></6,a,5*a)> 

Exemplo 2: Para array multidimensional

 import numpy as np a=np.arange(12) b=np.where([[True, False], [True, True]],[[1, 2], [3, 4]],[[9, 8], [7, 6]]) b  

Saída:

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

Exemplo 3: Transmissão de x, y e condição

 import numpy as np x, y = np.ogrid[:3, :4] a=np.where(x &gt; y, x, 10 + y) a  

Saída:

 array([[10, 11, 12, 13], [ 1, 11, 12, 13], [ 2, 2, 12, 13]])  

No código acima

  • Importamos numpy com o nome alternativo np.
  • Criamos um array 'a' usando a função np.arange().
  • Declaramos a variável 'b' e atribuímos o valor retornado da função np.where().
  • Passamos uma matriz multidimensional de booleanos como uma condição e x e y como matrizes de inteiros.
  • Por último, tentamos imprimir o valor de b.

Na saída, o valor x foi comparado ao valor y se satisfez a condição, então será impresso o valor x, caso contrário, será impresso o valor y, que foi passado como argumento na função where().

Exemplo 4: Transmitindo valor específico

 x=np.array([[0,1,2],[0,2,5],[0,4,8]]) y=np.where(x<4,x,-2) y < pre> <p> <strong>Output:</strong> </p> <pre> array([[ 0, 1, 2], [ 0, 2, -2], [ 0, -2, -2]]) </pre> <hr></4,x,-2)>