How to use array as native indices in Numpy
This works in MATLAB:
>> p = [1, 0, 2, 4, 3, 6, 5]; >> p(p+1) ans = 0 1 2 3 4 5 6
Is there a way to do the same in NumPy? I cannot figure out how:
>>> 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]
At this point, the interpreter seems to enter an endless loop. This also causes an infinite loop:
>>> [p[:,i] for i in p]
But this works:
>>> [p[:,i] for in range(0,6)]
So this is something about using a matrix member as native indices causing a problem. Is this a bug in Python? Or am I doing something wrong?
source to share
Only integers can be used as matrix or matrix indexes. The default type for a matrix initialized in this way is float.
You can use numpy.array
not a 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])
Or you can explicitly change your matrix to an integer type:
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
is a specialized class for 2D matrices. In particular, you cannot index a 2D matrix with a single integer, because - well - it's two-dimensional and you need to specify two integers, hence the need for an extra 0-index in the second example.
source to share