我已经看到了nonzero(a),(a)和arg where(a)之间的帖子差。什么时候使用哪个?而且我真的不明白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))
函数在哪里的定义:根据条件,从X或Y返回元素。但这对我来说也没有意义
那么,输出的含义是什么?
np.where
返回满足给定条件的索引。在您的情况下,您要询问Z
中的值不是0
的索引(例如Python将任何非0
值视为True
)。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),)
希望会有所帮助。