【python】numpy.where功能详解-位置函数

首先看源码,如下:

where(condition, [x, y])

Return elements, either from `x` or `y`, depending on `condition`.
If only `condition` is given, return ``condition.nonzero()``.

Parameters
----------
condition : array_like, bool
    When True, yield `x`, otherwise yield `y`.
x, y : array_like, optional
    Values from which to choose. `x`, `y` and `condition` need to be
    broadcastable to some shape.

Returns
-------
out : 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.

    If only `condition` is given, return the tuple
    ``condition.nonzero()``, the indices where `condition` is True.

Notes
-----
If `x` and `y` are given and input arrays are 1-D, `where` is
equivalent to::

    [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]

1、如果只是给定condition,则返回None

xx = np.arange(5)

np.where(True)
Out[262]: (array([0], dtype=int64),)

2、对于一维数组,返回condition下的位置

values = np.arange(2,5)

values
Out[281]: array([2, 3, 4])

np.where(values>3)
Out[282]: (array([2], dtype=int64),)

3、对于一维的数据,如果是一维,相当于[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]。输入条件,类数组形式,若判断结果成立则返回x,否则为y。

xx
Out[266]: array([0, 1, 2, 3, 4])

yy
Out[267]: array([1, 2, 3, 4, 5])

np.where(True,xx,yy)
Out[268]: array([0, 1, 2, 3, 4])

np.where(xx<3,xx,yy)
Out[269]: array([0, 1, 2, 4, 5])

4、对于多维数组,第一部分为矩阵行的坐标,第二部分为矩阵列的坐标。当条件对象维高维,按照二维矩阵操作,判断其中对象。

np.where([[True, False], [True, True]],
         [[1, 2], [3, 4]],
         [[9, 8], [7, 6]])
array([[1, 8],
       [3, 4]])
#返回的第一个array是行坐标数据,第二个array是列坐标数据。
np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))

x = np.arange(9.).reshape(3, 3)
np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))  想当于x[2,0] x[2,1] x[2,2]三个数值的位置

x[np.where( x > 3.0 )]               # Note: result is 1D.
array([ 4.,  5.,  6.,  7.,  8.])

np.where(x < 5, x, -1)               # Note: broadcasting.小于5的情况下,返回x的值;否则返回-1。
array([[ 0.,  1.,  2.],
       [ 3.,  4., -1.],
       [-1., -1., -1.]])

5、np.isin (数组 , 条件值) 找出数组中多个数字的位置

Find the indices of elements of `x` that are in `goodvalues`.
goodvalues = [3, 4, 7]
ix = np.isin(x, goodvalues)
ix
array([[False, False, False],
       [ True,  True, False],
       [False,  True, False]])
np.where(ix)
(array([1, 1, 2]), array([0, 1, 1]))
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值