[Numpy-discussion] Accessing rank-0 array value?

Tim Hochberg tim.hochberg at cox.net
Tue Jun 8 08:44:10 CDT 2004


[SNIP]

>>>>a[0]
>>>>        
>>>>
>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>IndexError: Too many indices
>
>by something like:
>
>  
>
>>>>a[0]
>>>>        
>>>>
>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>IndexError: rank-0 arrays don't accept integer indices. Use '()' (empty tuple)
>instead.
>
This seems like a sensible idea. One might further restrict this and 
only raise it when a rank-0 array is indexed with zero, which is the 
only real case that causes confusion. In that case, I suggest the error 
message similar to:

IndexError: Too many indices (Use A[()] to get scalar from rank-0 array A)


>In order to provide an universal accessor to numarray objects, what about
>adding a .toscalar() (or .toobject()) method to them? That would return a
>python object whether you are using rank-0 arrays, regular arrays,
>CharArrays or RecArrays. That object would be the minimal python container
>that would keep the values inside these objects. In case of rank-0 arrays it
>would return a Bool, Int, Float or Complex. For a regular array, a list
>(perhaps a tuple?). For CharArrays, a list (tuple?) of strings. And for
>RecArrays a list (tuple) of tuples.


That's an interesting idea. `tolist` doesn't work on rank-0 arrays, 
sensibly enough. I would expect something called toscalar to only work 
on rank-0 arrays. I don't like that since I would like to see fewer 
special cases for rank-0 arrays not less. However, something called 
`toobject` (or `topyobject`, `tocoreobject`, etc) could return a core 
python object that was equivalent to the original array, which I believe 
is what you describe above. For example, after:

obj = anArray.toobject()
type = anArray.type()
newArray = numarray.array(obj, type)

`newArray` would always be equal to `anArray` in both value and type. 
The implementation of toobject could be as simple as:

    def toobject(self):
       if self.rank == 0:
          return self[()]
       else:
          return self.tolist()

I'm not entirely convinced it's a good idea yet; I'd have to see some 
use cases, but it's an interesting idea in any event.


>Incidentally, I've noted an inconsistency in the .tostring behaviour:
>
>  
>
>>>>a=array(126)
>>>>a.tostring()
>>>>        
>>>>
>''
>  
>
Interesting. That's better than the memory error I get with 
Numarray-0.8. Or the indefinite hang I get with numarray 0.9.

>while I would expect a return value like:
>
>  
>
>>>>chr(126)
>>>>        
>>>>
>'~'
>  
>
I think it should actually be returning the same things as 
array([126]).tostring(). That is:

'\x80\x00\x00\x00'


[SNIP]

Regards,

-tim





More information about the Numpy-discussion mailing list