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

Sebastien Bardeau Sebastien.Bardeau at obs.u-bordeaux1.fr
Fri Oct 20 08:25:49 CDT 2006

```> 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")
>
Ok thanks. Actually that was also the solution I found. But this is much
more complicated when arrays are N dimensional with N>1, and above all
if user asks for a slice in one or more dimension. Here is how I
redefine the __getitem__ method for my arrays. Remember that the goal is
to return a 0-d array rather than a numpy.scalar when I extract a single
element out of a N-dimensional (N>=1) array:

def __getitem__(self,index): # Index may be either an int or a tuple
# Index length:
if type(index) == int: # A single element through first dimension
ilen = 1
index = (index,)    # A tuple
else:
ilen = len(index)
# Array rank:
arank = len(self.shape)
# Check if there is a slice:
for i in index:
if type(i) == slice:
hasslice = True
else:
hasslice = False
# Array is already a 0-d array:
if arank == 0 and index == (0,):
return self[()]
elif arank == 0:
raise IndexError, "0-d array has only one element at index 0."
# This will return a single element as a 0-d array:
elif arank == ilen and hasslice:
# This ugly thing returns a numpy 0-D array AND NOT a numpy scalar!
# (Numpy scalars do not share their data with the parent array)
newindex = list(index)
newindex[0] = slice(index[0],index[0]+1,None)
newindex = tuple(newindex)
return self[newindex].reshape(())
# This will return a n-D subarray (n>=1):
else:
return self[index]

Well... I do not think this is very nice. Someone has another idea? My
question in my first post was: is there a way to get a single element of
an array into
a 0-d array which shares memory with its parent array?

Sebastien

-------------------------------------------------------------------------
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