• numpy 学习:数组的查找


    1,查找最大值或最小值所在的索引

    按照特定的轴查找最大值或最小值的索引

    numpy.argmax(a, axis=None, out=None, *, keepdims=<no value>)
    numpy.argmin(a, axis=None, out=None, *, keepdims=<no value>)

    举个例子,查找最小值的索引:

    >>> a = np.arange(6).reshape(2,3) + 10
    >>> a
    array([[10, 11, 12],
           [13, 14, 15]])
    >>> np.argmin(a)
    0
    >>> np.argmin(a, axis=0)
    array([0, 0, 0])
    >>> np.argmin(a, axis=1)
    array([0, 0])

    2,查找非0元素的索引

    numpy.argwhere(a)

    举个例子,查找数组中大于0的元素的索引:

    >>> x = np.arange(6).reshape(2,3)
    >>> x
    array([[0, 1, 2],
           [3, 4, 5]])
    >>> np.argwhere(x>1)
    array([[0, 2],
           [1, 0],
           [1, 1],
           [1, 2]])

    3,查找操作

    查找操作是指按照特定的条件对数组元素进行三值运算

    where()函数对每一个元素执行三值运算:当满足condition 时,返回x;否则,返回y

    numpy.where(condition[, x, y])

    举个例子,对于一维数组,当元素值小于5时,返回原值;当元素值大于5时,乘以10返回:

    >>> 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])

    4,抽取元素

    返回满足条件的数据元素,当参数condition为True,返回该位置的元素:

    numpy.extract(condition, arr)

    举个例子,extract()函数和掩码索引数组的功能相同:

    >>> arr = np.arange(12).reshape((3, 4))
    >>> arr
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11]])
    >>> condition = np.mod(arr, 3)==0
    >>> condition
    array([[ True, False, False,  True],
           [False, False,  True, False],
           [False,  True, False, False]])
    >>> np.extract(condition, arr)
    array([0, 3, 6, 9])
    If condition is boolean:
    
    >>>
    >>> arr[condition]
    array([0, 3, 6, 9])

    参考文档:

    作者悦光阴
    本文版权归作者和博客园所有,欢迎转载,但未经作者同意,必须保留此段声明,且在文章页面醒目位置显示原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    python pyinotify模块详解
    lastpass密码管理工具使用教程
    MAMP 环境下安装Redis扩展
    SourceTree使用方法
    Mac securecrt 破解
    Memcache 安装
    Warning: setcookie() expects parameter 3 to be long, string given
    SQLSTATE[HY000] [2002] Connection refused
    插件管理无法访问
    光栅化渲染器
  • 原文地址:https://www.cnblogs.com/ljhdo/p/15766774.html
Copyright © 2020-2023  润新知