如何检查NumPy数组中是否存在指定的值
有时我们需要测试某些值是否存在于一个数组中。使用Numpy数组,我们可以很容易地找到特定值是否存在。为此,我们使用 “in “运算符。in “操作符用于检查某些元素和值是否存在于一个给定的序列中,从而返回布尔值 “True “和 “False”。
示例 1:
# importing Numpy package
import numpy as np
# creating a Numpy array
n_array = np.array([[2, 3, 0],
[4, 1, 6]])
print("Given array:")
print(n_array)
# Checking whether specific values
# are present in "n_array" or not
print(2 in n_array)
print(0 in n_array)
print(6 in n_array)
print(50 in n_array)
print(10 in n_array)
输出:
Given array:
[[2 3 0]
[4 1 6]]
True
True
True
False
False
在上面的例子中,我们使用’in’操作符检查Numpy数组’n_array’中是否有2,0,6,50,10的值。
示例 2:
# importing Numpy package
import numpy as np
# creating a Numpy array
n_array = np.array([[2.14, 3, 0.5],
[4.5, 1.2, 6.2],
[20.2, 5.9, 8.8]])
print("Given array:")
print(n_array)
# Checking whether specific values
# are present in "n_array" or not
print(2.14 in n_array)
print(5.28 in n_array)
print(6.2 in n_array)
print(5.9 in n_array)
print(8.5 in n_array)
输出:
Given array:
[[ 2.14 3. 0.5 ]
[ 4.5 1.2 6.2 ]
[20.2 5.9 8.8 ]]
True
False
True
True
False
在上面的例子中,我们检查Numpy数组’n_array’中是否有2.14, 5.28, 6.2, 5.9, 8.5的值。
示例 3:
# importing Numpy package
import numpy as np
# creating a Numpy array
n_array = np.array([[4, 5.5, 7, 6.9, 10],
[7.1, 5.3, 40, 8.8, 1],
[4.4, 9.3, 6, 2.2, 11],
[7.1, 4, 5, 9, 10.5]])
print("Given array:")
print(n_array)
# Checking whether specific values
# are present in "n_array" or not
print(2.14 in n_array)
print(5.28 in n_array)
print(8.5 in n_array)
输出:
Given array:
[[ 4. 5.5 7. 6.9 10. ]
[ 7.1 5.3 40. 8.8 1. ]
[ 4.4 9.3 6. 2.2 11. ]
[ 7.1 4. 5. 9. 10.5]]
False
False
False
在上面的例子中,我们检查Numpy数组’n_array’中是否有2.14,5.28,8.5的值。