Python 如何在Numpy中将数组用作自己的索引
这在MATLAB中起作用:Python 如何在Numpy中将数组用作自己的索引,python,matrix,numpy,indices,Python,Matrix,Numpy,Indices,这在MATLAB中起作用: >> p = [1, 0, 2, 4, 3, 6, 5]; >> p(p+1) ans = 0 1 2 3 4 5 6 有没有办法在NumPy做同样的事情?我不知道该怎么做: >>> p = mat([1, 0, 2, 4, 3, 6, 5]) >>> p[p] Traceback (most recent call last): File "<stdin&
>> p = [1, 0, 2, 4, 3, 6, 5];
>> p(p+1)
ans =
0 1 2 3 4 5 6
有没有办法在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]
但这是可行的:
>>> [p[:,i] for in range(0,6)]
因此,使用矩阵成员作为自己的索引是导致问题的原因。这是Python中的一个bug吗?还是我做错了什么?只有整数可以用作数组或矩阵索引。像这样初始化的矩阵的默认类型是float 您可以使用
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])
或者,您可以将矩阵显式更改为整数类型:
In [5]: x = np.matrix(x).astype(int)
In [6]: x[0, x]
Out[7]: matrix([[0, 1, 2, 3, 4, 5, 6]])
A
numpy.matrix
是专为2D矩阵设计的专业课程。特别是,你不能用一个整数为2D矩阵编制索引,因为它是二维的,你需要指定两个整数,因此在第二个例子中需要额外的0索引。我不知道为什么@Katriealex删除了他的答案,但这是正确的:使用np.array
,而不是np.matrix
,你的问题就消失了p=np.array([1,0,2,4,3,6,5]);p[p]
给出了预期的结果。@larsmans不幸的是,它比这更复杂,我不明白为什么。例如,np.asarray(np.asmatrix(x))[x]
崩溃,尽管x[x]
没有崩溃。我认为这是一个相当神秘的问题,因为选择了错误的索引类型,但我仍然在思考。@larsmans好的,我明白了。忽略我=)它似乎与数组/矩阵中的数据类型有关,而不是它是矩阵还是数组本身<代码>p=np.mat([0,1,2,4,3,6,5]).astype(int);p[0,p]也做了正确的事情。我对答案进行了编辑以反映这一点-一旦通过同行评审,我会将其标记为正确。还要注意,矩阵可以直接使用x=np.matrix(x,int)
创建为整数矩阵,而不是使用.astype(int)
。
In [5]: x = np.matrix(x).astype(int)
In [6]: x[0, x]
Out[7]: matrix([[0, 1, 2, 3, 4, 5, 6]])