python - numpy where 函数的基础知识,它对数组有什么作用?

标签 python arrays numpy

我看过帖子Difference between nonzero(a), where(a) and argwhere(a). When to use which?而且我真的不明白 numpy 模块中 where 函数的用法。

例如我有这段代码

import numpy as np

Z =np.array( 
    [[1,0,1,1,0,0],
     [0,0,0,1,0,0],
     [0,1,0,1,0,0],
     [0,0,1,1,0,0],
     [0,1,0,0,0,0],
     [0,0,0,0,0,0]])
print Z
print np.where(Z)

给出:

(array([0, 0, 0, 1, 2, 2, 3, 3, 4], dtype=int64), 
 array([0, 2, 3, 3, 1, 3, 2, 3, 1], dtype=int64))

where函数的定义是: 根据条件从 x 或 y 返回元素。但这对我来说也没有意义

那么输出到底是什么意思呢?

最佳答案

np.where 返回满足给定条件的索引。在您的情况下,您要求索引 Z 中的值不是 0 (例如,Python 将任何非 0 值视为)。 Z 的结果是:

(0, 0) # top left
(0, 2) # third element in the first row
(0, 3) # fourth element in the first row
(1, 3) # fourth element in the second row
...    # and so on

np.where 在以下情况下开始变得有意义:

a = np.arange(10)
np.where(a > 5) # give me all indices where the value of a is bigger than 5
# a > 5 is a boolean mask like [False, False, ..., True, True, True]
# (array([6, 7, 8, 9], dtype=int64),)

希望对您有所帮助。

关于python - numpy where 函数的基础知识,它对数组有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21287592/

相关文章:

python - 应用 "group by"后选择第一个或最后一个 n 组

python - 重写内置类型的特殊方法

python - 如何解决Python列表索引超出范围错误?

Python 的新 `functools.cached_property` 错误或限制?

java - 如何使两个数组随机相等

python - 生成具有不同范围的嵌套列表

python - 如何在python中不使用[]将列表写入文件

java - 为什么这没有给出错误?

linq - LINQ for LIKE查询数组元素

python - 与 CPython 相比,Numba 和 Cython 没有显着提高性能,也许我使用不正确?