How Do You Know The Shape and Size Of a Numpy Array ?


How Do You Know The Shape and Size Of a Numpy Array ?

Table Of Contents:

  1. ndarray.ndim
  2. ndarray.size
  3. ndarray.shape

(1) ndarray.ndim

  • ndarray.ndim will tell you the number of axes, or dimensions, of the array.

Example-1:

a = np.array([1, 2, 3])
a
array([1, 2, 3])
a.ndim

Output:

1

Example-2:

b = np.array([[1,4],[3,2]])
b
array([[1, 4],
       [3, 2]])
b.ndim

Output:

2

Example-3:

c = np.array([[[1,4],[3,2]]])
c
array([[[1, 4],
        [3, 2]]])
c.ndim

Output:

3

Example-4:

y = np.zeros((2, 3, 4))
y
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]])
y.ndim

Output:

3

(2) ndarray.size

  • ndarray.size will tell you the total number of elements of the array. This is the product of the elements of the array’s shape.

Example-1:

a = np.array([1, 2, 3])
a
array([1, 2, 3])
a.size

Output:

3

Example-2:

b = np.array([[1,4],[3,2]])
b
array([[1, 4],
       [3, 2]])
b.size

Output:

4

Example-3:

c = np.array([[[1,4],[3,2]]])
c
array([[[1, 4],
        [3, 2]]])
c.size

Output:

4

Example-4:

y = np.zeros((2, 3, 4))
y
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]])
y.size

Output:

24

(3) ndarray.shape

  • ndarray.shape will display a tuple of integers that indicate the number of elements stored along each dimension of the array. If, for example, you have a 2-D array with 2 rows and 3 columns, the shape of your array is (2, 3).

Example-1:

a = np.array([1, 2, 3])
a
array([1, 2, 3])
a.shape

Output:

(3,)

Example-2:

b = np.array([[1,4],[3,2]])
b
array([[1, 4],
       [3, 2]])
b.shape

Output:

(2, 2)

Example-3:

c = np.array([[[1,4],[3,2]]])
c
array([[[1, 4],
        [3, 2]]])
c.shape

Output:

(1, 2, 2)

Example-4:

y = np.zeros((2, 3, 4))
y
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]])
y.shape

Output:

(2, 3, 4)

Leave a Reply

Your email address will not be published. Required fields are marked *