获取元素大于 X 的 NumPy 数组的行号
让我们看看如何获取至少有一项大于指定值 X 的 numpy 数组的行号。因此,为了完成此任务,我们将一起使用 numpy.where() 和 numpy.any() 函数。
Syntax: numpy.where(condition[, x, y])
Return: [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere.
Syntax: numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)
Return: [ndarray, optional]Output array with same dimensions as Input array, Placed with result
例子 :
Arr = [[1,2,3,4,5],
[10,-3,30,4,5],
[3,2,5,-4,5],
[9,7,3,6,5]]
and X = 6 then output is [ 0, 2 ].
Here,
[[1,2,3,4,5],
no element is greater than 6 so output is [0].
[10,-3,30,4,5],
10 is greater than 6 so output is [0].
[3,2,5,-4,5],
no element is greater than 6 so output is [0, 2].
[4,7,3,6,5]]
7 is greater than 6 so output is [0, 2].
下面是实现:
Python3
# importing library
import numpy
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
[10, -3, 30, 4, 5],
[3, 2, 5, -4, 5],
[9, 7, 3, 6, 5]
])
# declare specified value
X = 6
# view array
print("Given Array:\n", arr)
# finding out the row numbers
output = numpy.where(numpy.any(arr > X,
axis = 1))
# view output
print("Result:\n", output)
输出:
Given Array:
[[ 1 2 3 4 5]
[10 -3 30 4 5]
[ 3 2 5 -4 5]
[ 9 7 3 6 5]]
Result:
(array([1, 3], dtype=int64),)