[Numpy-discussion] Behavior of array scalars
Christopher Barker
Chris.Barker at noaa.gov
Fri Feb 17 12:24:01 CST 2006
Hi all,
It just dawned on my that the numpy array scalars might give something I
have wanted once in a while: mutable scalars. However, it seems that we
almost, but no quite, have them. A few questions:
>>> import numpy as N
>>> N.__version__
'0.9.2'
>>> N.array(5)
array(5)
>>>
>>> x = N.array(5)
>>> x.shape
()
So it looks like a scalar.
>>> y = x
Now I have two names bound to the same object.
>>> x += 5
I expect this to change the object in place.
>>> x
10
but what is this? is it no longer an array?
>>> y
array(10)
y changed, so it looks like the object has changed in place.
>>> type(x)
<type 'int32_arrtype'>
>>> type(y)
<type 'numpy.ndarray'>
So why did x += 5 result in a different type of object?
Also:
I can see that we could use += and friends to mutate an array scalar,
but what if I want to set it's value, as a mutation, like:
>>> x = N.array((5,))
>>> x
array([5])
>>> x[0] = 10
>>> x
array([10])
but I can't so that with an array scalar:
>>> x = N.array(5)
>>> x
array(5)
>>> x[0] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: 0-d arrays can't be indexed.
>>> x[] = 10
File "<stdin>", line 1
x[] = 10
^
SyntaxError: invalid syntax
>>> x[:] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: cannot slice a scalar
Is there a way to set the value in place, without resorting to:
>>> x *= 0
>>> x += 34
I think it would be really handy to have a full featured, mutable scalar.
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
NOAA/OR&R/HAZMAT (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the Numpy-discussion
mailing list