This article “Python where How to use function ” Most people don't quite understand the knowledge points of the article , So I made up the following summary for you , Detailed content , The steps are clear , It has certain reference value , I hope you can gain something after reading this article , Let's take a look at this article “Python where How to use function ” Article bar .
where The function is numpy In the library , Usually you need to load first numpy library , Call this function again . There are two basic call syntax for functions , One is :
import numpy as npnp.where(arry)
here ,np.where Output function arry in “ really ” Coordinates of values (‘ really ’ It can also be understood as non 0). Or say np.where Function from arry Returns elements that meet certain conditions . such as , It will return the index position of the value that meets the specific conditions .
The other is :
import numpy as npnp.where(cond, x, y)
here ,np.where Function satisfies cond Conditional output x, Not satisfied with output y. In order to make everyone right where A clearer understanding of function definitions , Next, it will be explained with specific examples , It's convenient for you to understand and remember .
y = np.array([1, 5, 6, 8, 1, 7, 3, 6, 9])print(np.where(y>5))
Get the results :
(array([2, 3, 5, 7, 8], dtype=int64),)
here ,np.where Function returns a value greater than 5 Index position of .
y = np.array(range(1, 10))print(y)print(np.where(y>5, 'm_5', 'lq_5'))
Get the results :
[1 2 3 4 5 6 7 8 9]
['lq_5' 'lq_5' 'lq_5' 'lq_5' 'lq_5' 'm_5' 'm_5' 'm_5' 'm_5']
y Is an initial value of 1, The final value is 9, In steps of 1 Equal difference sequence of . here ,np.where Function satisfies y>5 Output ’m_5’, Not satisfied with output ’lq_5’.
print(np.arange(10))print(np.where(np.arange(10)<5, ' Eat an apple ', ' Eat durian '))
Get the results :
[0 1 2 3 4 5 6 7 8 9]
[‘ Eat an apple ’ ‘ Eat an apple ’ ‘ Eat an apple ’ ‘ Eat an apple ’ ‘ Eat an apple ’ ‘ Eat durian ’ ‘ Eat durian ’ ‘ Eat durian ’ ‘ Eat durian ’ ‘ Eat durian ’]
here ,np.where Function satisfies np.arange(10) The median value is less than 5 Output ’ Eat an apple ’, Not satisfied with output ’ Eat durian ’.
y = np.array(range(1, 10))print(y)print(np.where(np.mod(y, 2)==0, '2b', 'n_2b'))
Get the results :
[1 2 3 4 5 6 7 8 9]
['n_2b' '2b' 'n_2b' '2b' 'n_2b' '2b' 'n_2b' '2b' 'n_2b']
here ,np.where Function satisfies y Divide the mean value by 2 Remainder is 0 Output ’2b’, Not satisfied with output ’n_2b’.
x = np.array([[0, 1, 2], [3, 0, 0], [6, 0, 8]])print(x[np.where(x)])
Get the results :
[1 2 3 6 8]
here ,np.where The function takes out x Central Africa 0 Count , Generate a new sequence .
That's about “Python where How to use function ” The content of this article , I believe we all have a certain understanding , I hope the content shared by Xiaobian will be helpful to you , If you want to know more about it , Please pay attention to the Yisu cloud industry information channel .