获取元素大于X的NumPy数组的行数
让我们看看如何获得一个数组中至少有一项大于指定值X的行数。因此,为了完成这项任务,我们将同时使用numpy.where()和numpy.any()函数。
语法: numpy.where(condition[, x, y])
返回: [ndarray or tuple of ndarrays] 如果同时指定了x和y,输出数组包含条件为True的x的元素,以及其他地方的y的元素。
语法: numpy.any(a, axis = None, out = None, keepdims = class numpy._globals._NoValue at 0x40ba726c)
返回: [ndarray, optional]与输入数组尺寸相同的输出数组,与结果放在一起。
示例 :
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].
以下是实施情况。
# 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),)