[Numpy-discussion] array - dimension size of 1-D and 2-D examples
Derek Homeier
derek at astro.physik.uni-goettingen.de
Sat Dec 30 07:36:32 EST 2017
On 30 Dec 2017, at 11:37 am, Vinodhini Balusamy <me.vinob at gmail.com> wrote:
>
> Case 2:
> >>>
> >>> x12 = np.array([[1,2,3],[]])
> >>> x12.ndim
> 1
> >>> print(x12)
> [list([1, 2, 3]) list([])]
> >>>
> In case 2, I am trying to understand why it becomes 1 dimentional ?!?!
>
>
> Case 3:
> >>>
> >>> x12 = np.array([1,2,3])
> >>> x12.ndim
> 1
> >>> print(x12)
> [1 2 3]
> >>>
> This seems reasonable to me to be considered as 1 dimensional.
>
> Would like to understand case 2 a bit more to get to know if i am missing something.
> Will be much appreciated if someone to explain me a bit.
>
Welcome to the crowd!
You cannot create a regular 2-dimensional integer array from one row of length 3
and a second one of length 0. Thus np.array chooses the next most basic type of
array it can fit your input data in - you will notice in case 2 the array actually has two
elements of type ‘list’, and you can verify that
In [1]: x12 = np.array([[1,2,3],[]])
In [2]: x12.dtype
Out[2]: dtype('O')
In [3]: x12.shape
Out[3]: (2,)
i.e. it has created an array of dtype ‘object’, which is probably not what you expected
(and nothing you could perform standard arithmetic operations on:
In [4]: x12+1
TypeError: can only concatenate list (not "int") to list
HTH
Derek
More information about the NumPy-Discussion
mailing list