numpy.where
numpy.
where
(condition[, x, y])
Return elements, either from x or y, depending on condition.
If only condition is given, return condition.nonzero()
.
Returns:
out : ndarray or tuple of ndarrays
If both x and y are specified, the output array contains elements of xwhere condition is True, and elements from y elsewhere.
If only condition is given, return the tuple condition.nonzero()
, the indices where condition is True.
如果二维数组数组使用where的话返回的也是一个二维数组,准确的来说一维数组返回的也是一个二维数组
x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )] # Note: result is 1D.
array([ 4., 5., 6., 7., 8.])
>>> np.where(x < 5, x, -1) # 值替换
array([[ 0., 1., 2.],
[ 3., 4., -1.],
[-1., -1., -1.]])
(array([2, 2, 2]), array([0, 1, 2]))
第三行的1,2,3列大于五