python - numpy.where() 在这个例子中究竟是如何选择元素的?

标签 python python-3.x numpy

来自 numpy docs

>>> np.where([[True, False], [True, True]],
    ...          [[1, 2], [3, 4]],
    ...          [[9, 8], [7, 6]])
array([[1, 8],
       [3, 4]])

我假设 [[True, False], [True, True]] 部分是条件并且 [[1, 2], [3, 4] 是否正确][[9, 8], [7, 6]] 根据文档参数分别是 x 和 y。

那么下面例子中的函数究竟是如何选择元素的呢?

另外,为什么这些例子中的元素类型是一个列表?

>>> np.where([[True, False,True], [False, True]], [[1, 2,56], [3, 4]], [[9, 8,79], [7, 6]])
array([list([1, 2, 56]), list([3, 4])], dtype=object)
>>> np.where([[False, False,True,True], [False, True]], [[1, 2,56,69], [3, 4]], [[9, 8,90,100], [7, 6]])
array([list([1, 2, 56, 69]), list([3, 4])], dtype=object)

最佳答案

在第一种情况下,每个术语都是一个 (2,2) 数组(或者更确切地说,可以组成这样一个数组的列表)。对于条件中的每个 True,它返回 x 中的相应项、[[1 -][3,4]],以及对于每个 False,来自 y [[- 8][- -]]

的术语

在第二种情况下,列表参差不齐

In [1]: [[True, False,True], [False, True]]
Out[1]: [[True, False, True], [False, True]]
In [2]: np.array([[True, False,True], [False, True]])
Out[2]: array([list([True, False, True]), list([False, True])], dtype=object)

数组是 (2,),有 2 个列表。当转换为 bool 值时,一个 2 元素数组,两者都为 True。只有空列表才会产生 False。

In [3]: _.astype(bool)
Out[3]: array([ True,  True])

where 然后只返回 x 值。

第二种情况是可以理解的,但却是病态的。

更多详情

让我们用一个更简单的例子来更详细地演示where。相同条件数组:

In [57]: condition = np.array([[True, False], [True, True]])
In [58]: condition
Out[58]: 
array([[ True, False],
       [ True,  True]])

单参数版本,相当于condition.nonzero():

In [59]: np.where(condition)
Out[59]: (array([0, 1, 1]), array([0, 0, 1]))

有些人发现更容易可视化该元组的转置 - condition 为 True 的 3 对坐标:

In [60]: np.argwhere(condition)
Out[60]: 
array([[0, 0],
       [1, 0],
       [1, 1]])

现在最简单的版本有 3 个参数,带有标量值。

In [61]: np.where(condition, True, False)   # same as condition
Out[61]: 
array([[ True, False],
       [ True,  True]])
In [62]: np.where(condition, 100, 200)
Out[62]: 
array([[100, 200],
       [100, 100]])

可视化此操作的一个好方法是使用两个掩码分配。

In [63]: res = np.zeros(condition.shape, int)
In [64]: res[condition] = 100
In [65]: res[~condition] = 200
In [66]: res
Out[66]: 
array([[100, 200],
       [100, 100]])

另一种方法是用 y 值初始化一个数组,并将非零值填入 x 值。

In [69]: res = np.full(condition.shape, 200)
In [70]: res
Out[70]: 
array([[200, 200],
       [200, 200]])
In [71]: res[np.where(condition)] = 100
In [72]: res
Out[72]: 
array([[100, 200],
       [100, 100]])

如果 xy 是数组,而不是标量,则此掩码赋值将需要改进,但希望这对开始有所帮助。

关于python - numpy.where() 在这个例子中究竟是如何选择元素的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54490040/

相关文章:

python - 适用于 OS X 的 Numpy-MKL

python - 从文本文件中读取元组

django - python : can't open file 'manage.py' : [Errno 2] No such file or directory

python - 具有不同数据类型的 Numpy 数组表现得很奇怪

python - 从 numpy 数组中获取第 n 个元素

python - 在 Python 中检测 * 可用 * CPU 数量的可移植方法

Python:在 matplotlib.pyplot 上绘制子列表

python-3.x - 如何使用 scipy optimization 找到 3 个参数和数据点列表的最小卡方?

python - Snakemake 在配置中声明临时文件

python - 从文件加载数据集,与 sklearn/numpy 一起使用,包括标签