[Numpy-discussion] Matching 0-d arrays and NumPy scalars
Damian Eads
eads@soe.ucsc....
Thu Feb 21 06:44:54 CST 2008
In MATLAB, scalars are 1x1 arrays, and thus they can be indexed. There
have been situations in my use of Numpy when I would have liked to index
scalars to make my code more general.
It's not a very pressing issue for me but it is an interesting issue.
Whenever I index an array with a sequence or slice I'm guaranteed to get
another array out. This consistency is nice.
In [1]: A=numpy.random.rand(10)
In [2]: A[range(0,1)]
Out[2]: array([ 0.88109759])
In [3]: A[slice(0,1)]
Out[3]: array([ 0.88109759])
In [3]: A[[0]]
Out[3]: array([ 0.88109759])
However, when I index an array with an integer, I can get either a
sequence or a scalar out.
In [4]: c1=A[0]
Out[4]: 0.88109759
In [5]: B=numpy.random.rand(5,5)
In [5]: c2=B[0]
Out[5]: array([ 0.81589633, 0.9762584 , 0.72666631, 0.12700816,
0.40653243])
Although c1 and c2 were derived by integer-indexing two different arrays
of doubles, one is a sequence and the other is a scalar. This lack of
consistency might be confusing to some people, and I'd imagine it
occasionally results in programming errors.
Damian
Travis E. Oliphant wrote:
> Hi everybody,
>
> In writing some generic code, I've encountered situations where it would
> reduce code complexity to allow NumPy scalars to be "indexed" in the
> same number of limited ways, that 0-d arrays support.
>
> For example, 0-d arrays can be indexed with
>
> * Boolean masks
> * Ellipses x[...] and x[..., newaxis]
> * Empty tuple x[()]
>
> I think that numpy scalars should also be indexable in these particular
> cases as well (read-only of course, i.e. no setting of the value would
> be possible).
>
> This is an easy change to implement, and I don't think it would cause
> any backward compatibility issues.
>
> Any opinions from the list?
>
>
> Best regards,
>
> -Travis O.
More information about the Numpy-discussion
mailing list