花式索引的 Numpy 广播

Numpy broadcasting of fancy index

程序 1 中的 np.newaxis 如何在 numpy 数组的索引中工作?为什么会这样?

计划 1:

import numpy as np
x_id = np.array([0, 3])[:, np.newaxis]
y_id = np.array([1, 3, 4, 7])
A = np.zeros((6,8))
A[x_id, y_id] += 1 
print(A)

结果 1:

[[ 0.  1.  0.  1.  1.  0.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  1.  0.  1.  1.  0.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.]]

newaxisx_id数组转为列向量,与np.array([[0],[3]])相同。

因此您在 [0,3][1,3,4,7] 的笛卡尔积处索引 A。或者换句话说,第 0 行和第 3 行、第 1、3、4 和 7 列最终为 1。

另见np.ix_([0,3], [1,3,4,7])

In [832]: np.stack(np.meshgrid([0,3],[1,3,4,7],indexing='ij'),axis=2)
Out[832]: 
array([[[0, 1],
        [0, 3],
        [0, 4],
        [0, 7]],

       [[3, 1],
        [3, 3],
        [3, 4],
        [3, 7]]])

+=1 设置要小心一点;如果索引重复,您可能得不到预期的结果,或者会出现循环。