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

Sebastien Bardeau Sebastien.Bardeau at
Fri Oct 20 04:42:26 CDT 2006


I am confused with Numpy behavior with its scalar or 0-d arrays objects:

 >>> numpy.__version__
 >>> a = numpy.array((1,2,3))
 >>> b = a[:2]
 >>> b += 1
 >>> b
array([2, 3])
 >>> a
array([2, 3, 3])
 >>> type(b)
<type 'numpy.ndarray'>

To this point all is ok for me: subarrays share (by default) memory with 
their parent array. But:

 >>> c = a[2]
 >>> c += 1
 >>> c
 >>> a
array([2, 3, 3])
 >>> type(c)
<type 'numpy.int32'>
 >>> id(c)
 >>> c += 1
 >>> id(c)

That's really confusing, because slices (from __getslice__ method) are 
not copies (they share memory), and items (single elements from 
__getitem__ ) are copies to one of the scalar objects provided by Numpy. 
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
 >>> a
array([2, 3, 3])
 >>> type(d)
<type 'numpy.ndarray'>
 >>> d.shape
 >>> id(d)
 >>> d += 1
 >>> id(d)

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?

Thx for your help,


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
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo

More information about the Numpy-discussion mailing list