[Numpy-discussion] can int and float exists in one array?(about difference in indexing Matlab matrix and Numpy array)
Tim Hochberg
tim.hochberg at ieee.org
Mon Nov 27 15:11:57 EST 2006
Zhang Sam wrote:
> Hi, there
>
> I have a practical problem. For some reason, I hope int and float can
> exist one array as shown in matlab code.
> ---------------------------------------------------------------------------
> >> x = [2 2.5 3.5; 1 2.6 3.5]
>
> x =
>
> 2.0000 2.5000 3.5000
> 1.0000 2.6000 3.5000
>
> >> y = x(:,2)
>
> y =
>
> 2.5000
> 2.6000
>
> >> y(x(:,1))
>
> ans =
>
> 2.6000
> 2.5000
> ------------------------------------------------------------------------------------
>
> 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. Please show me .
What are you trying to do here? Is the first column always going to
consist of integral values? If so, I'd point you to record arrays. Using
those you could store the first column (more or less -- you'd actually
access is slightly differently) as integers and the other two columns as
floats. Alternatively, you could simply store things as two separate
arrays, one int and one float. Or is something else going on?
You could store all of your values as python objects, but I would
recommend against it in almost all cases. Object arrays are cantankerous
beasts, you will be chewing up a lot of memory unnecessarily and you'll
loose any opportunities for speeding things up using numpy. It is true
that, if you are doing the majority of your calculations in standard
Python, it is faster at least for small arrays, to keep things in object
arrays. However, if you are doing most of your computation that way, it
is likely that something is badly wrong in the sense that you are not
utilizing numpy as it's meant to be used.
-tim
More information about the NumPy-Discussion
mailing list