np.where() usage analysis

np.where() usage analysis

1. Grammar description

  • np.where(condition,x,y)
    When there are three parameters in where, the first parameter represents the condition. When the condition is true, the where method returns x. When the condition is not true, where returns y.

  • np.where(condition)
    When there is only one parameter in where, that parameter represents the condition. When the condition is true, where returns the coordinates of each element that meets the condition. The returned value is in the form of a tuple, and the coordinates are in tuple form. The form shows how many dimensions the original array usually has, and the output tuple contains several arrays, corresponding to the coordinates of each dimension of the elements that meet the conditions.

  • Multi-condition condition
    -& means AND, | means OR. For example, a = np.where((a>0)&(a<5), x, y), when a>0 and a<5 are satisfied, the value of x is returned. When a>0 and a<5 are not satisfied, the value of x is returned. When , return the value of y.
    Note: x, y must maintain the same dimensions as a, so that the values ​​of the array can correspond one to one.

2.Example

(1) A parameter

import numpy as np
a = np.arange(0, 100, 10)
b = np.where(a < 50) 
c = np.where(a >= 50)[0]
print(a)
print(b) 
print(c) 

The result is as follows:

[ 0 10 20 30 40 50 60 70 80 90]
(array([0, 1, 2, 3, 4]),)
[5 6 7 8 9]

Explanation:
b is the element position that meets the condition of less than 50. The data type of b is tuple.
c is the element position that meets the condition of greater than or equal to 50. The data type of c is numpy.ndarray.

(2) Three parameters

a = np.arange(10)
b = np.arange(0,100,10)

print(np.where(a > 5, 1, -1))
print(b)

print(np.where((a>3) & (a<8),a,b))

c=np.where((a<3) | (a>8),a,b)
print(c)

The result is as follows:

[-1 -1 -1 -1 -1 -1  1  1  1  1]
[ 0 10 20 30 40 50 60 70 80 90]
[ 0 10 20 30  4  5  6  7 80 90]
[ 0  1  2 30 40 50 60 70 80  9]

Explanation:
np.where(a > 5, 1, -1), if the condition is satisfied, it is 1, if it is not satisfied, it is -1
np.where((a>3) & (a<8),a,b), if the condition is satisfied, it is -1 a, if b is not satisfied, the dimensions of a and b are the same.
Note:
& | With and or, each condition must use parentheses, otherwise an error will be reported

c=np.where((a<3 | a>8),a,b)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Guess you like

Origin blog.csdn.net/qq_39065491/article/details/132731504