简体   繁体   中英

How to use an array as its own 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 thing in NumPy? I can't 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]

The interpreter seems to go into an infinite loop at this point. This also causes an infinite loop:

>>> [p[:,i] for i in p]

But this works:

>>> [p[:,i] for in range(0,6)]

So it is something about using a matrix member as its own indices that causes the problem. Is this a bug in Python? Or am I doing something wrong?

Only integers can be used as array or matrix indices. The default type for a matrix initialised like that is float.

You can use a 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 specialised class designed for 2D matrices. In particular, you can't 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 the extra 0 index in the second example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM