[Numpy-discussion] scalar recordarrays

Francesc Altet faltet@carabos....
Mon Mar 19 04:00:14 CDT 2007

El ds 17 de 03 del 2007 a les 18:53 -0400, en/na Matthew Koichi Grimes
va escriure:
> I've found that if I have a record array of shape [] (i.e. a scalar 
> recarray), I can't set its fields.
>  >>> recarr
> recarray((0.0, 0.0, 0.0),
>       dtype=[('x', '<f8'), ('dx', '<f8'), ('delta', '<f8')])
>  >>> recarr.x[...] = 1.0
> TypeError: object does not support item assignment
> In the above, recarr.x returned a float "0.0", then attempted the 
> assignment "0.0 = 1.0", which raised the TypeError. This is in contrast 
> with the behavior of scalar ndarrays, where the above works as expected:
>  >>> arr
> array(0.0)
>  >>> arr[...] = 1.0
>  >>> arr
> array(1.0)

You are having a couple of confusions here. The first is in terms of
nomenclature: in your examples, 'recarr' and 'arr' are *rank-0* ndarrays
and not scalar objects. Although both rank-0 and scalar objects do
contain the same information, they behave differently: a rank-0 array
behaves more similar to an array and the scalar more like a python

The other confusion is that, while 'recarr' is a rank-0 array, recarr.x
is actually a true scalar, and you can assign to it in the regular
scalar way:

In [67]:recarr.x
In [68]:recarr.x = 2
In [69]:recarr.x

Having said this, I think there is a real inconsistency here that I
think it is worth to note. Let's see the next recarray behaviour:

In [70]:recarr2=numpy.rec.array([(1.0, 0, 3)], dtype)
In [71]:recarr2.x
Out[71]:array([ 1.])
In [72]:recarr2.x[...] = 0
In [73]:recarr2.x
Out[73]:array([ 0.])

i.e. 'recarr2' is a rank-1 array, and 'recarr2.x' is a rank-1 array (and
thus, assigning works as regular array assigns). In the same way, with a
rank-0 'recarr', 'recarr.x' should return a rank-0 array (for
consistency), but it doesn't:

In [74]:recarr=numpy.rec.array((1.0, 0, 3), dtype)
In [75]:recarr.x
In [76]:type(recarr.x)
Out[76]:<type 'numpy.float64'>

While I find this inconsistent, I'm not sure whether it should be be
fixed or not because the boundaries between rank-0 and scalar objects
are always a bit fuzzy. Travis can probably bring more light here.


Francesc Altet    |  Be careful about using the following code --
Carabos Coop. V.  |  I've only proven that it works, 
www.carabos.com   |  I haven't tested it. -- Donald Knuth

More information about the Numpy-discussion mailing list