python|numpy where的使用 ,返回值的使用

2017-10-21  本文已影响1391人  五长生

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.]])
image.png

(array([2, 2, 2]), array([0, 1, 2]))

第三行的1,2,3列大于五

关于一维数组的返回值,这样表示

image.png image.png
上一篇 下一篇

猜你喜欢

热点阅读