Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

missing dimension in numpy array shape [duplicate]

Tags:

python

numpy

what is the difference between the following two (why is the dimension missing in the first case):

zeros((3,)).shape
Out[67]: (3,)

zeros((3,1)).shape
Out[68]: (3, 1)
like image 385
Alex Kreimer Avatar asked Apr 02 '14 11:04

Alex Kreimer


People also ask

How do I add a dimension to a NumPy array?

You can add new dimensions to a NumPy array ndarray (= unsqueeze a NumPy array) with np. newaxis , np. expand_dims() and np. reshape() (or reshape() method of ndarray ).

How do I get my NumPy array size back?

len() is the Python built-in function that returns the number of elements in a list or the number of characters in a string. For numpy. ndarray , len() returns the size of the first dimension.


1 Answers

The shape of an array is a tuple of its dimensions. An array with one dimension has a shape of (n,). A two dimension array has a shape of (n,m) and a three dimension array has a shape of (n,m,k) and so on.

When you change from (3,) to (3,1) you are changing from 1 dimension to 2 dimension.

You can keep adding dimensions in this way (You can check the number of dimensions of an array using .ndim):

One dimension:

>>> a = np.zeros((2))
array([ 0.,  0.])
>>> a.shape
(2,)
>>> a.ndim
1

Two dimensions:

>>> b = np.zeros((2,2))
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> b.shape
(2,2)
>>> b.ndim
2

Three dimensions:

>>> c = np.zeros((2,2,2))
array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.]]])
>>> c.shape
(2,2,2)
>>> c.ndim
3

Four dimensions:

>>> d = np.zeros((2,2,2,2))
array([[[[ 0.,  0.],
         [ 0.,  0.]],

        [[ 0.,  0.],
         [ 0.,  0.]]],


       [[[ 0.,  0.],
         [ 0.,  0.]],

        [[ 0.,  0.],
         [ 0.,  0.]]]])
>>> d.shape
(2,2,2,2)
>>> d.ndim
4
like image 91
atomh33ls Avatar answered Oct 16 '22 12:10

atomh33ls