Home >Backend Development >Python Tutorial >Python detailed analysis of np.where() code application
[Related recommendations: Python3 video tutorial]
A kind of np.where(condition, x, y)
, that is, condition is the condition. When the condition is met, the output is x, if the condition is not met, the output is y. Directly enter the code:
a = np.arange(10) //array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print(np.where(a > 5, 1, -1)) //array([-1, -1, -1, -1, -1, -1, 1, 1, 1, 1])
Above It is quite easy to understand, but the example on the official website is not easy to understand, as shown below:
np.where([[True,False], [True,True]], [[1,2], [3,4]], [[9,8], [7,6]]) // 输出 array([[1, 8], [3, 4]])
It can be understood in this way. The bool value in the first line represents the condition, which means whether to take the value. First, look at [ True, False], that is, the first True value means that the first row takes the value 1 in [1, 2] in the first row, instead of taking the 9 below, False means not taking the value in [1, 2] in the first row 2, and take the 8 in the second row [9, 8]. The following is the same as [3, 4].
For the convenience of understanding, let’s give another example:
a = 10 >>> np.where([[a > 5,a < 5], [a == 10,a == 7]], [["chosen","not chosen"], ["chosen","not chosen"]], [["not chosen","chosen"], ["not chosen","chosen"]]) //array([['chosen', 'chosen'], ['chosen', 'chosen']], dtype='<U10')
The first row a> 5True, then take the first value of the first row, ace523c7b8482a09a9795861645b3d5b5=0 and data<=2, np.ones_like(data)the value of the corresponding coordinates will be returned if it is satisfied, no If satisfied, the value of np.zeros_like(data) corresponding coordinates will be returned. Of course, x and y can be changed to other values, as long as they have the same size as the conditions.
【Related recommendations: Python3 video tutorial】
The above is the detailed content of Python detailed analysis of np.where() code application. For more information, please follow other related articles on the PHP Chinese website!