在原始和列上选择相同 idx 的 Numpy

Numpy selection of the same idx on both raw and columns

今天遇到一个奇怪的选择:

import numpy as np

A = np.array([[1, 2, 3], 
              [4, 5, 6], 
              [7, 8, 9]])

idx = [0, 1]

A[idx, idx]
A[idx, :][:, idx]

我不明白第一个选择的输出A[idx, idx]array([1, 5])

因为 A[[0,1],:] 回到你 row zero and one 然后 A[[0,1],[0,1]]row zero 你得到 column zero 而在 row one 你得到 column one.

A[[0,1], :]
# array([[1, 2, 3],
#        [4, 5, 6]])

A[[0,1],[0,1]]
# array([1, 5])

您正在这样做:

A[[0, 1], [0, 1]]

基本上是:

[A[0, 0], A[1, 1]]

在您的示例数据中当然是 [1, 5]。

NumPy 称之为“整数高级索引”。

In [85]: A = np.arange(1,10).reshape(3,3)
In [86]: idx=[0,1]

这个select是一个'diagonal',2个列表的值是成对的:

In [87]: A[idx,idx]
Out[87]: array([1, 5])

如果要阻止,请使用 ix_:

In [88]: A[np.ix_(idx,idx)]
Out[88]: 
array([[1, 2],
       [4, 5]])

ix_ 将输入转换为以多维方式相互广播的元组:

In [89]: np.ix_(idx,idx)
Out[89]: 
(array([[0],
        [1]]),
 array([[0, 1]]))

ogrid 从切片中产生相同的东西:

In [90]: np.ogrid[:2,:2]
Out[90]: 
[array([[0],
        [1]]),
 array([[0, 1]])]

mgrid 创建相同,但完全扩展为 3d 数组。这可能有助于可视化 ix_ 元组如何广播到 select 块:

In [91]: np.mgrid[:2,:2]
Out[91]: 
array([[[0, 0],
        [1, 1]],

       [[0, 1],
        [0, 1]]])

在 MATLAB (idx,idx) select 中,块,但是 select 对角线需要将 2d 索引转换为 1d,subs2indnumpy 块索引有点复杂,但更通用。