[Numpy-discussion] can int and float exists in one array?(about difference in indexing Matlab matrix and Numpy array)

Robert Kern robert.kern at gmail.com
Mon Nov 27 11:49:38 EST 2006


Zhang Sam wrote:
> However in python with numpy, the similar code is as follows.
> ------------------------------------------------------------------------------------------
> x = array([[2, 2.5, 3.5],[1, 2.6, 3.5]])
>>>> x
> array([[ 2. ,  2.5,  3.5],
>        [ 1. ,  2.6,  3.5]])
>>>> y = x[:,1]
>>>> y
> array([ 2.5,  2.6])
>>>> y.shape=2,1
>>>> y
> array([[ 2.5],
>        [ 2.6]])
>>>> y[x[:,0],0]
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> IndexError: arrays used as indices must be of integer (or boolean) type
> -----------------------------------------------------------------------------------------------------
>  
> MATLAB can treat the 1.0,2.00,......as int 1 2,.....
> How to realize this matlab code in python? Maybe it exist a simple way.

y[x[:,0].astype(int),0]

By and large, in Python and numpy, floats are not accepted in places where
integers are required, like indexing. The meaning is ambiguous, so we refuse the
temptation to guess what the programmer meant.

As a corollary, if you find that you are putting index values into an array with
floating point values, you are doing something wrong. At least, you are trying
to use Matlab idioms that simply aren't used in Python or numpy. We can't tell
you how to "translate" the Matlab idioms into Python idioms without knowing what
you intended to do at a slightly higher level, though.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list