如何检查 NumPy 数组中是否存在指定值?
有时我们需要测试数组中是否存在某些值。使用 Numpy 数组,我们可以轻松找到特定值是否存在。为此,我们使用“ in ”运算符。 “ in ”运算符用于检查给定序列中是否存在某些元素和值,从而返回布尔值“真”和“假”。
示例 1:
Python3
# 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)
Python3
# 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)
Python3
# 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:
[[2 3 0]
[4 1 6]]
True
True
True
False
False
在上面的示例中,我们使用“ in ”运算符检查 Numpy 数组“ n_array ”中是否存在值 2、0、6、50、10。
示例 2:
蟒蛇3
# 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:
蟒蛇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 。