如何在Numpy中使用数组作为自己的索引

Tom*_*Tom 3 python numpy matrix indices

这适用于MATLAB:

>> p = [1, 0, 2, 4, 3, 6, 5];
>> p(p+1)

ans = 

     0   1   2   3   4   5   6
Run Code Online (Sandbox Code Playgroud)

有没有办法在NumPy中做同样的事情?我无法弄清楚如何:

>>> p = mat([1, 0, 2, 4, 3, 6, 5])
>>> p[p]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\numpy\matrixlib\defmatrix.py", line 305, in __getitem__
    out = N.ndarray.__getitem__(self, index)
IndexError: index (1) out of range (0<=index<0) in dimension 0
>>> p[:,p]
Run Code Online (Sandbox Code Playgroud)

在这一点上,解释器似乎进入了无限循环.这也会导致无限循环:

>>> [p[:,i] for i in p]
Run Code Online (Sandbox Code Playgroud)

但这有效:

>>> [p[:,i] for in range(0,6)]
Run Code Online (Sandbox Code Playgroud)

因此,使用矩阵成员作为自己的索引会导致问题.这是Python中的错误吗?或者我做错了什么?

Kat*_*iel 5

只有整数可以用作数组或矩阵索引.初始化的矩阵的默认类型是float.

你可以用a numpy.array而不是numpy.matrix:

In [2]: import numpy as np
In [3]: x = np.array([1, 0, 2, 4, 3, 6, 5])
In [4]: x[x]
Out[4]: array([0, 1, 2, 3, 4, 5, 6])
Run Code Online (Sandbox Code Playgroud)

或者您可以明确地将矩阵更改为整数类型:

In [5]: x = np.matrix(x).astype(int)
In [6]: x[0, x]
Out[7]: matrix([[0, 1, 2, 3, 4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)

A numpy.matrix是专为2D矩阵设计的专业类.特别是,您不能使用单个整数索引2D矩阵,因为 - 好 - 它是二维的,您需要指定两个整数,因此在第二个示例中需要额外的0索引.