Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy where函数的基础知识,它对数组有什么作用?_Python_Arrays_Numpy - Fatal编程技术网

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

Python numpy where函数的基础知识,它对数组有什么作用?,python,arrays,numpy,Python,Arrays,Numpy,我看过这篇文章,但我并不真正理解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,

我看过这篇文章,但我并不真正理解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。其中
返回满足给定条件的索引。在您的例子中,您要求的是
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.其中
在以下情况下开始有意义:

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

希望这能有所帮助。

当你把它叫做
np时,where(condition,x,y)
它就是你所引用的。如果省略
x
y
参数,则等于
np.nonzero
。numpy.where是否循环整个数组?