NumPy 如何检查数组中是否存在指定的值
我们在Python语言中有不同的模块和函数可用来检查给定NumPy数组中是否存在指定的值。
NumPy是Numerical Python的缩写,它是一个用于执行数学、统计和科学计算的Python库。NumPy数组的结果以数组的形式返回。数组可以是一维、二维等,最多可以达到32维。
NumPy库提供了许多模块和函数,帮助我们进行科学计算和数学计算。
让我们逐个查看每种方法,以检查NumPy数组中是否存在指定的值。
使用“in”关键字
以下示例检查指定的值是否存在于NumPy数组中。我们有一个关键字,即 in ,用于检查特定元素是否存在于定义的数据结构中。
import numpy as np
arr = np.array([10,30,2,40.3,56,456,32,4])
print("The Original array:",arr)
if 4 in arr:
print("The element is present in the array.")
else:
print("The element is not present in the array")
输出
当我们运行上面的代码时,将生成以下输出,它显示元素存在于数组中。
The Original array: [ 10. 30. 2. 40.3 56. 456. 32. 4. ]
The element is present in the array.
示例
这是另一个示例,用于检查给定的值是否存在于定义的数组中。
import numpy as np
arr = np.array([10,30,2,40.3,56,4,56,3,2,4])
print("The Original array:",arr)
if 4 or 56 in arr:
print("The element is present in the array.")
else:
print("The element is not present in the array")
输出
以下是使用in关键字检查给定值是否存在于数组中的输出。
The Original array: [10. 30. 2. 40.3 56. 4. 56. 3. 2. 4. ]
The element is present in the array.
使用np.isin()函数
Numpy库提供了一个名为 isin() 的函数,用于检查给定的值是否存在于定义的数组中。要检查的值也应该是数组格式。输出将以True或False的布尔格式返回。
示例
在这个例子中,我们将传递要检查的数组和要传递给 isin() 函数的值,输出将以布尔值True或False的格式返回。
import numpy as np
arr = np.array([[10,30,2,40.3],[56,4,56,3]])
print("The Original array:",arr)
values = np.array([10,30,2,40.3])
output = np.isin(arr, values)
print(output)
输出
以下是 isin() 函数的输出结果,该函数返回布尔值。
The Original array: [[10. 30. 2. 40.3]
[56. 4. 56. 3. ]]
[[ True True True True]
[False False False False]]
示例
下面的示例显示了如何检查指定值是否存在于定义的数组中。
import numpy as np
arr = np.array([[[10,30],[2,40.3]],[[56,4],[56,3]]])
print("The Original array:",arr)
values = np.array([1,40.3])
output = np.isin(arr, values)
print(output)
输出
以下是上述代码的输出结果。
The Original array: [[[10. 30. ]
[ 2. 40.3]]
[[56. 4. ]
[56. 3. ]]]
[[[False False]
[False True]]
[[False False]
[False False]]]
使用np.where()函数
where() 是numpy库提供的一个函数,允许您在numpy数组中搜索特定的值。该函数返回数组中值存在的元素的索引。
示例
要检查NumPy数组中是否存在特定值,我们使用NumPy数组提供的 where() 函数。我们将数组和要搜索的值作为参数传递给此函数。
import numpy as np
arr = np.array([[[10,30],[2,40.3]],[[56,4],[56,3]]])
print("The Original array:",arr)
output = np.where(arr == 3)
print(output)
输出
当我们运行上述代码时,我们会看到以下输出 –
The Original array: [[[10. 30. ]
[ 2. 40.3]]
[[56. 4. ]
[56. 3. ]]]
(array([1]), array([1]), array([1]))