如何在多个条件下使用NumPy where()

948 阅读1分钟

你可以使用以下方法来使用NumPywhere()函数的多个条件。

方法1:使用where()与OR

#select values less than five or greater than 20
x[np.where((x < 5) | (x > 20))]

方法2:使用where()与AND

#select values greater than five and less than 20
x[np.where((x > 5) & (x < 20))]

下面的例子展示了如何在实践中使用每种方法。

方法1:使用where()与OR

下面的代码显示了如何选择一个NumPy数组中小于5大于20的每一个值:

import numpy as np

#define NumPy array of values
x = np.array([1, 3, 3, 6, 7, 9, 12, 13, 15, 18, 20, 22])

#select values that meet one of two conditions
x[np.where((x < 5) | (x > 20))]

array([ 1,  3,  3, 22])

请注意,NumPy数组中的四个值都小于5大于20。

你也可以使用size函数来简单地找到有多少个值符合其中一个条件:

#find number of values that are less than 5 or greater than 20
(x[np.where((x < 5) | (x > 20))]).size

4

方法2:使用where()与AND

下面的代码显示了如何选择NumPy数组中大于5 小于20的每个值:

import numpy as np

#define NumPy array of values
x = np.array([1, 3, 3, 6, 7, 9, 12, 13, 15, 18, 20, 22])

#select values that meet two conditions
x[np.where((x > 5) & (x < 20))]

array([6,  7,  9, 12, 13, 15, 18])

输出数组显示了原始NumPy数组中大于5小于20的七个值。

再一次,你可以使用size函数来查找有多少个值符合这两个条件:

#find number of values that are greater than 5 and less than 20
(x[np.where((x > 5) & (x < 20))]).size

7

其他资源

下面的教程解释了如何在NumPy中进行其他常见操作:

如何计算NumPy数组的模式
如何查找NumPy数组中的值的索引
如何在NumPy数组上映射一个函数