# Numpy-scalars vs Numpy 0-d arrays: copy or not copy?

Francesc Altet faltet at carabos.com
Fri Oct 20 05:55:57 CDT 2006

```A Divendres 20 Octubre 2006 11:42, Sebastien Bardeau va escriure:
[snip]
> I can understand that numpy.scalars do not provide inplace operations
> (like Python standard scalars, they are immutable), so I'd like to use
>
> 0-d Numpy.ndarrays. But:
>  >>> d = numpy.array(a[2],copy=False)
>  >>> d += 1
>  >>> d
>
> array(4)
>
>  >>> a
>
> array([2, 3, 3])
>
>  >>> type(d)
>
> <type 'numpy.ndarray'>
>
>  >>> d.shape
>
> ()
>
>  >>> id(d)
>
> 169621280
>
>  >>> d += 1
>  >>> id(d)
>
> 169621280
>
> This is not a solution because d is a copy since construction time...
> My question is: is there a way to get a single element of an array into
> a 0-d array which shares memory with its parent array?

One possible solution (there can be more) is using ndarray:

In [47]: a=numpy.array([1,2,3], dtype="i4")
In [48]: n=1    # the position that you want to share
In [49]: b=numpy.ndarray(buffer=a[n:n+1], shape=(), dtype="i4")
In [50]: a
Out[50]: array([1, 2, 3])
In [51]: b
Out[51]: array(2)
In [52]: b += 1
In [53]: b
Out[53]: array(3)
In [54]: a
Out[54]: array([1, 3, 3])

Cheers,

--
>0,0<   Francesc Altet     http://www.carabos.com/
V   V   Cárabos Coop. V.   Enjoy Data
"-"

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier