[Numpy-discussion] converting scalar to array with dimension 1

Bill Baxter wbaxter@gmail....
Fri Mar 30 13:57:38 CDT 2007


atleast_1d will do the trick

In [11]: a = 3
In [12]: a = atleast_1d(a)
In [13]: shape(a)
Out[13]: (1,)
In [14]: a.shape   # also works ;-)
Out[14]: (1,)
In [15]: a[0]
Out[15]: 3

--bb

On 3/30/07, Mark Bakker <markbak@gmail.com> wrote:
> Hello list -
>
> I have a function that normally accepts an array as input, but sometimes a
> scalar.
> I figured the easiest way to make sure the input is an array, is to make it
> an array.
> But if I make a float an array, it has 0 dimension, and I can still not do
> array manipulation on it.
>
> >>> a = 3
> >>> a = array(a)
> >>> shape(a)
> ()
> >>> a[0]
> Traceback (most recent call last):
>   File "<pyshell#121>", line 1, in ?
>     a[0]
> IndexError: 0-d arrays can't be indexed
>
> What would be the best (and easiest, this is for an intro class I am
> teaching) way
> to convert a to an array (recall, most of the time a is already an array).
>
> Thanks for your help, Mark
>
>
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
>


More information about the Numpy-discussion mailing list