np.where()函数的详细使用介绍

看了很多博客,见到的没有一个给说清楚了,这里做个记录。这是python提供的函数说明:
在这里插入图片描述

Help on function where in module numpy:

where(...)
    where(condition, [x, y])
    
    Return elements chosen from `x` or `y` depending on `condition`.
    
    .. note::
        When only `condition` is provided, this function is a shorthand for
        ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
        preferred, as it behaves correctly for subclasses. The rest of this
        documentation covers only the case where all three arguments are
        provided.
    
    Parameters
    ----------
    condition : array_like, bool
        Where True, yield `x`, otherwise yield `y`.
    x, y : array_like
        Values from which to choose. `x`, `y` and `condition` need to be
        broadcastable to some shape.
    
    Returns
    -------
    out : ndarray
        An array with elements from `x` where `condition` is True, and elements
        from `y` elsewhere.
    
    See Also
    --------
    choose
    nonzero : The function that is called when x and y are omitted
    
    Notes
    -----
    If all the arrays are 1-D, `where` is equivalent to::
    
        [xv if c else yv
         for c, xv, yv in zip(condition, x, y)]
    
    Examples
    --------
    >>> a = np.arange(10)
    >>> a
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> np.where(a < 5, a, 10*a)
    array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])
    
    This can be used on multidimensional arrays too:
    
    >>> np.where([[True, False], [True, True]],
    ...          [[1, 2], [3, 4]],
    ...          [[9, 8], [7, 6]])
    array([[1, 8],
           [3, 4]])
    
    The shapes of x, y, and the condition are broadcast together:
    
    >>> x, y = np.ogrid[:3, :4]
    >>> np.where(x < y, x, 10 + y)  # both x and 10+y are broadcast
    array([[10,  0,  0,  0],
           [10, 11,  1,  1],
           [10, 11, 12,  2]])
    
    >>> a = np.array([[0, 1, 2],
    ...               [0, 2, 4],
    ...               [0, 3, 6]])
    >>> np.where(a < 4, a, -1)  # -1 is broadcast
    array([[ 0,  1,  2],
           [ 0,  2, -1],
           [ 0,  3, -1]])

就是说,当只传入condition参数时,等价于np.nonzero()

Help on function nonzero in module numpy:

nonzero(a)
    Return the indices of the elements that are non-zero.
    
    Returns a tuple of arrays, one for each dimension of `a`,
    containing the indices of the non-zero elements in that
    dimension. The values in `a` are always tested and returned in
    row-major, C-style order.
    
    To group the indices by element, rather than dimension, use `argwhere`,
    which returns a row for each non-zero element.
    
    .. note::
    
       When called on a zero-d array or scalar, ``nonzero(a)`` is treated
       as ``nonzero(atleast1d(a))``.
    
       .. deprecated:: 1.17.0
    
          Use `atleast1d` explicitly if this behavior is deliberate.
    
    Parameters
    ----------
    a : array_like
        Input array.
    
    Returns
    -------
    tuple_of_arrays : tuple
        Indices of elements that are non-zero.
    
    See Also
    --------
    flatnonzero :
        Return indices that are non-zero in the flattened version of the input
        array.
    ndarray.nonzero :
        Equivalent ndarray method.
    count_nonzero :
        Counts the number of non-zero elements in the input array.
    
    Notes
    -----
    While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
    recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
    will correctly handle 0-d arrays.
    
    Examples
    --------
    >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
    >>> x
    array([[3, 0, 0],
           [0, 4, 0],
           [5, 6, 0]])
    >>> np.nonzero(x)
    (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
    
    >>> x[np.nonzero(x)]
    array([3, 4, 5, 6])
    >>> np.transpose(np.nonzero(x))
    array([[0, 0],
           [1, 1],
           [2, 0],
           [2, 1]])
    
    A common use for ``nonzero`` is to find the indices of an array, where
    a condition is True.  Given an array `a`, the condition `a` > 3 is a
    boolean array and since False is interpreted as 0, np.nonzero(a > 3)
    yields the indices of the `a` where the condition is true.
    
    >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    >>> a > 3
    array([[False, False, False],
           [ True,  True,  True],
           [ True,  True,  True]])
    >>> np.nonzero(a > 3)
    (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
    
    Using this result to index `a` is equivalent to using the mask directly:
    
    >>> a[np.nonzero(a > 3)]
    array([4, 5, 6, 7, 8, 9])
    >>> a[a > 3]  # prefer this spelling
    array([4, 5, 6, 7, 8, 9])
    
    ``nonzero`` can also be called as a method of the array.
    
    >>> (a > 3).nonzero()
    (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))

在这里插入图片描述

<think>好的,我现在要详细解释numpy.where函数的用法,并提供示例。首先,我需要回顾用户提供的引用内容,确保准确引用相关信息。根据用户提供的引用[^1][^2][^3],其中提到where函数用于条件筛选和元素替换,类似于SQL中的WHERE子句,还能处理多维数组。 首先,我应该从基本用法开始,说明where函数的三种参数形式:condition、x和y。引用[^1]提到,当只传入condition时,返回满足条件的索引;传入x和y时,进行元素替换。需要举例说明这两种情况,比如一维数组的条件索引和替换操作。 接着,多维数组的处理是重点,引用[^3]中的例子是二维数组,可以借鉴。比如创建一个二维数组,展示如何获取满足条件的元素坐标,以及如何替换元素。需要注意说明返回的元组结构,每个元素对应一个维度的索引数组。 然后,高级用法部分可以结合引用[^2]提到的布尔数组操作,比如多个条件组合使用,或者结合其他Numpy函数如logical_and/or。例如,筛选出大于某个值且小于另一个值的元素,并替换。 还要注意特殊情况的处理,比如condition的不同形状与x、y的广播机制。可能需要举例说明当x和y是标量时的替换情况,以及如何利用广播简化代码。 在示例代码部分,确保每个例子都有明确的注释和输出结果,帮助用户理解。比如,第一个例子展示一维数组的条件索引,第二个展示替换,第三个处理多维数组,第四个展示多条件组合。 最后,总结应用场景,强调where函数在数据清洗、条件替换和筛选中的实用性,并对比Python内置的列表推导式,突出Numpy的高效性。 需要检查所有LaTeX语法是否正确,行内公式用$...$,独立公式用$$...$$。同时,确保回答结构清晰,分点说明,并在适当位置添加引用标识。生成的相关问题要围绕where函数的深入应用,如性能优化、多条件处理、与其他函数的结合等。</think>### Numpy where函数详解 Numpy的`np.where`函数是数组操作中重要的条件筛选工具,支持**元素替换**和**索引定位**两种模式。以下从语法结构到具体应用场景逐步解析。 --- #### 一、函数语法 ```python numpy.where(condition[, x, y]) ``` - **`condition`**: 布尔类型数组,定义筛选条件 - **`x`**: 满足条件时替换的值(可选) - **`y`**: 不满足条件时替换的值(可选) 若仅传入`condition`,返回满足条件的**元素索引**;若传入`x``y`,则根据条件选择对应位置的`x``y`值[^3]。 --- #### 二、核心用法示例 ##### 1. 定位满足条件的索引(单条件) ```python import numpy as np arr = np.array([2, 5, 1, 8, 3]) indices = np.where(arr > 3) print(indices) # 输出:(array([1, 3]),) ``` 结果表示索引1和3的元素满足`arr > 3`,对应值5和8[^3]。 ##### 2. 元素替换(三元运算) ```python result = np.where(arr > 3, '符合', '不符合') print(result) # 输出:['不符合' '符合' '不符合' '符合' '不符合'] ``` 此处将大于3的元素替换为'符合',否则为'不符合'[^1]。 ##### 3. 多维数组处理 ```python matrix = np.array([[1, 9], [4, 5]]) rows, cols = np.where(matrix > 4) print("行索引:", rows) # 行索引: [0 1] print("列索引:", cols) # 列索引: [1 1] ``` 返回的`rows`和`cols`分别对应满足条件的行列坐标,可组合为`(0,1)`和`(1,1)`[^3]。 ##### 4. 多条件组合(逻辑运算符) ```python condition = (arr > 2) & (arr < 8) # 必须用位运算符&代替and result = np.where(condition, arr*2, -1) print(result) # 输出:[-1 10 -1 -1 6] ``` 此处将2-8之间的元素翻倍,其他设为-1[^2]。 --- #### 三、高级特性 1. **广播机制** 当`x``y`为标量时,自动广播至与`condition`相同形状: ```python np.where([[True, False], [False, True]], 100, -100) # 输出:[[100, -100], [-100, 100]] ``` 2. **嵌套条件** 通过多次调用实现复杂逻辑: ```python arr = np.random.randn(5) result = np.where(arr > 0, 1, np.where(arr < -1, -1, 0)) # 正数→1,小于-1→-1,其余→0 ``` --- #### 四、典型应用场景 - **数据清洗**:将异常值替换为特定数值 - **图像处理**:根据像素阈值生成二值图像 - **科学计算**:分段函数实现,如$f(x)=\begin{cases} x^2 & x>0 \\ 0 & \text{其他} \end{cases}$可写作`np.where(x>0, x**2, 0)` 与Python原生列表推导式相比,`np.where`在大型数组上速度提升显著[^1][^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值