我看过帖子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/