Array dimensionality

Introduction to NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

3D arrays

array_1_2D = np.array([[1, 2], [5, 7]])
array_2_2D = np.array([[8, 9], [5, 7]])
array_3_2D = np.array([[1, 2], [5, 7]])
array_3D = np.array([array_1_2D, array_2_2D, array_3_2D])

graphic of a 3D array

Introduction to NumPy

4D arrays

array_4D = np.array([array_A_3D, array_B_3D, array_C_3D, array_D_3D, array_E_3D,
                     array_F_3D, array_G_3D, array_H_3D, array_I_3D])

graphic of a 4D array

Introduction to NumPy

Vector arrays

 

Graphic showing that 1D arrays cannot be vertical or horizontal in NumPy

 

Graphic showing that 2D arrays can be vertical or horizontal in NumPy

Introduction to NumPy

Matrix and tensor arrays

 

  • A matrix has two dimensions

graphic of a matrix

 

  • A tensor has three or more dimensions

graphic of a tensor

Introduction to NumPy

Shapeshifting

 

Array attribute:

  • .shape

 

Array methods:

  • .flatten()
  • .reshape()
Introduction to NumPy

Finding an array's shape

array = np.zeros((3, 5))
print(array)
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])
array.shape
(3, 5)
Introduction to NumPy

Rows and columns

In 2D arrays...

  • Rows are the first dimension
  • Columns are the second dimension

2D array with row and column labels

Introduction to NumPy

Flattening an array

array = np.array([[1, 2], [5, 7], [6, 6]])
array.flatten()
array([1, 2, 5, 7, 6, 6])
Introduction to NumPy

Reshaping an array

array = np.array([[1, 2], [5, 7], [6, 6]])
array.reshape((2, 3))
array([[1, 2, 5],
       [7, 6, 6]])

 

array.reshape((3, 3))
ValueError: cannot reshape array of size 6 into shape (3,3)
Introduction to NumPy

Let's practice!

Introduction to NumPy

Preparing Video For Download...