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

3

我看过这篇文章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中的元素。但对我来说这并没有意义。

那么输出结果究竟是什么意思呢?


1
当你调用 np.where(condition, x, y) 时,它会执行你引用的操作。如果你省略了 xy 参数,它等同于 np.nonzero - Jaime
1个回答

2

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

希望这有所帮助。

numpy.where循环整个数组吗? - Rosenthal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接