problems with duplicating and slicing an array

Steven Bethard steven.bethard at gmail.com
Thu Jan 20 20:47:36 EST 2005


Yun Mao wrote:
> Hi python gurus,
>   I have some questions when I'm using python numeric:
> 
> 1. When I do v = u[:, :],  it seems u and v still point to the same
> memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well.
> What's the right way to duplicate an array? Now I have to do v =
> dot(u, identity(N)), which is kind of silly.

Hmm...  I don't know Numeric, but in numarray (Numeric's replacement), 
you just call the copy method:

py> u = na.arange(6, shape=(2, 3))
py> v = u.copy()
py> v[0,0] = 100
py> u
array([[0, 1, 2],
        [3, 4, 5]])
py> v
array([[100,   1,   2],
        [  3,   4,   5]])

> 2. Is there a way to do Matlab style slicing? e.g. if I have
>  i = array([0, 2])
>  x = array([1.1, 2.2, 3.3, 4.4])
>  I wish y = x(i) would give me [1.1, 3.3]

This also works exactly as you'd hope in numarray.

py> i = na.array([0, 2])
py> x = na.array([1.1, 2.2, 3.3, 4.4])
py> x[i]
array([ 1.1,  3.3])

Do you have any reason that you have to use Numeric?  Or can you upgrade 
to numarray?

Steve



More information about the Python-list mailing list