NumPy Arrays

category_1
category_2
category_3
category_4

Write a description of the lesson here.

Authors

Noor Sohail

Will Gammerdinger

Published

March 15, 2026

Keywords

keyword_1, keyword_2, keyword_3, keyword_4, keyword_5, keyword_6

Approximate time: XX minutes

Learning Objectives

In this lesson, we will:

  • Learning Objective 1
  • Learning Objective 2
  • Learning Objective 3

Overview of lesson

When doing XYZ…

NumPy Library

NumPy is a powerful library for numerical computing in Python. It is widely used to work with arrays and matrices. The implementation of these data structures and associated methods have been optimized for performance, making it a popular choice for scientific computing and data analysis. You can find the official documentation for NumPy here and you should consult it whenever there you need to run a specific task repeatedly to see if an function already exists for that task. You can also use the help() function in Python to get more information about a specific NumPy function or data structure.

1-dimensional Arrays

The most basic data structure in NumPy is the 1-dimensional array, which is similar to a list. You can create a 1-dimensional array using the numpy.array() function:

#Import numpy using the alias, np
import numpy as np

# Create a 1-dimensional numpy array called arr
arr = np.array([1, 2, 3, 4, 5])

# Print the numpy array 
print(arr)
[1 2 3 4 5]

One of the key advantages of NumPy arrays over Python lists is their greater efficiency for numerical operations. For example, you can easily perform element-wise operations on NumPy arrays. So if we were to add two arrays together, it would add each element of the first array to the corresponding element of the second array:

# Create another 1-dimensional numpy array called arr2
arr2 = np.array([10, 20, 30, 40, 50])

# Perform element-wise addition on arr and arr2 and assign the output to result
result = arr + arr2

# Print result array
print(result)
[11 22 33 44 55]

If we were to try to do this with Python lists, we would get a different result:

# Create two Python lists
list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]

# Attempt to perform element-wise addition (this will not work as expected)
result_list = list1 + list2

# Print the resulting list
print(result_list)
[1, 2, 3, 4, 5, 10, 20, 30, 40, 50]

Instead of adding two lists together element-wise, Python concatenates them (in order to concatenate arrays in NumPy, you would use the np.concatenate() function).

Additionally, if we were to investigate the dtype() of the NumPy array, we would find that it is a specific data type (e.g., int64 or float64). So, unlike lists which can contain different data types, the elements in NumPy arrays are all the same data type.

# Check the data type attribute of the NumPy array
arr.dtype
dtype('int64')

N-dimensional Arrays

Arrays are not just limited to 1 dimension; NumPy can also create and handle multi-dimensional arrays. For example, you can create a 2-dimensional array (also known as a matrix) while using the same numpy.array() function:

# Create a 2-dimensional array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6]])

# Print out the matrix
print(matrix)
[[1 2 3]
 [4 5 6]]

This again may seem familiar to a list of lists in Python, but it is important to note this is a NumPy array which has different properties and capabilities than a list of lists. For example, you can perform matrix operations on this 2-dimensional array, such as matrix multiplication (dot product).

# Create another 2-dimensional array (matrix)
matrix2 = np.array([[10, 20], [30, 40], [50, 60]])

# Perform matrix multiplication
result_matrix = np.dot(matrix, matrix2)

# Print out the result matrix
print(result_matrix)
[[220 280]
 [490 640]]

We can initialize a matrix of zeros or ones by using numpy.zeros() and numpy.ones() methods in as many dimensions as we want. Alternatively, we could use numpy.identity() to create an identity matrix.

Rows then columns

When accessing elements in a 2-dimensional array, the first index refers to the row and the second index refers to the column. So matrix[0, 1] would access the element in the first row and second column of the matrix.

Similarly, when initializing a matrix, the first number refers to the number of rows and the second number refers to the number of columns.

# Initialize a 3x3 matrix of zeros
zeros_matrix = np.zeros((3, 3))

# Print the zeros_matrix
print(zeros_matrix) 
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
# Initialize a 2x4 matrix of ones
ones_matrix = np.ones((2, 4))

# Print the ones_matrix
print(ones_matrix)
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]]
# Initialize a 3x3 identity matrix
identity_matrix = np.identity(3)
print(identity_matrix)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

The numpy.reshape() function is another flexible way to create arrays of varying shapes and sizes. We can use this in conjunction with numpy.arange() to create an array of a specific range of numbers and then reshape it into the desired dimensions.

# Create an array of integers from 0 to 9, then reshape it into a 2 x 5 matrix
matrix_arange = np.arange(10).reshape((2, 5))

# Print the matrix
print(matrix_arange)
[[0 1 2 3 4]
 [5 6 7 8 9]]

Indexing and Slicing Arrays

Arrays can be indexed and sliced in a similar way to lists with indices (again beginning with 0) and slicing syntax. So if we wanted to access the first element of a 1-dimensional array, we would use arr1[0]:

# Retrieve the first element of arr
first_element = arr[0]

# Print the retrieved element
print(first_element)
1

In a 2-dimensional array, the first index refers to the row and the second index refers to the column. So if we wanted to access the first row of a 2-dimensional array, we would use matrix[0]:

# Access the first row of a 2-dimensional array
first_row = matrix[0]

# Print the retrieved row
print(first_row)
[1 2 3]

If we wanted to access the element in the second row and third column of the matrix, we would use matrix[1, 2]:

# Retrieve the element in the second row and third column
element = matrix[1, 2]

# Print the retrieved element
print(element)
6

So far, this is quite similar to lists. Arrays differ because they have more advanced indexing and slicing capabilities, allowing you to more easily select specific elements or subsets of the array based on certain conditions. This is particularly useful when working with large datasets as it allows you to efficiently filter and wrangle the data.

# Create a 1-dimensional array
arr = np.array([1, 2, 3, 4, 5])

# Select elements greater than 3
filtered_arr = arr[arr > 3]

# Print the selected elements
print(filtered_arr)
[4 5]
  1. A question to evaluate Learning Objective 1
  2. A followup question to question #1

Useful NumPy Functions

Base Python is somewhat limited when it comes to numerical operations. The NumPy library provides a broader range of mathematical tools. For example, you can quickly calculate the mean, median, and standard deviation of an array with the numpy.mean(), numpy.median(), and numpy.std() functions:

# Create a 1-dimensional array
arr = np.array([2, 7, 9.5, 5, 7, 3.2])

# Calculate mean of arr
mean = np.mean(arr)

# Calculate median of arr
median = np.median(arr)

# Calculate standard deviation of arr
std_dev = np.std(arr)

# Print an f-string (Python inteprets items with {}) with the mean, median and standard deviation
print(f"Mean: {mean}, Median: {median}, Standard Deviation: {std_dev}")
Mean: 5.616666666666667, Median: 6.0, Standard Deviation: 2.523500654954453

NumPy has other functions for performing mathematical operations on arrays, such as numpy.sum(), numpy.prod(), numpy.cumsum(), numpy.cumprod(), numpy.square(), numpy.sqrt(), numpy.max(), numpy.min(). All these functions allow you to perform operations across the entire array or along specific axes.

Subsection 2A

Useful NumPy functions to get the shape and dimensions of arrays include:

  1. numpy.shape(): This function returns the dimensions of the array as a tuple. For example, numpy.shape on a 2 x 3 2-dimensional array would return (2, 3).
  2. numpy.ndim(): This function returns the number of dimensions of the array.
  3. numpy.size(): This function returns the total number of elements in the array. For example, numby.shape on a 3 x 4 2-dimensional array would return 12 (3 rows x 4 columns = 12 elements).
  4. numpy.dtype(): This function returns the data type of the elements in the array.

Other useful NumPy functions to change the shape of an array include:

  1. numpy.T(): This function transposes the array by swapping its rows and columns along with its associated data. For example, a 1 x 3 array like [[1, 2, 3]] would be transposed to a 3 x 1 array [[1], [2], [3]].
  2. numpy.newaxis(): This function allows you to add a new axis to an array, transforming a 1D array into a 2D array or a 2D array into a 3D array. For example, numpy.newaxis() can convert a 1D array with three columns into a 2D array with one row and three columns.

Subsection 2B

  1. A question to evaluate Learning Objective 2
  2. A followup question to question #1

Topic 3

Subsection 3A

Subsection 3B

  1. A question to evaluate Learning Objective 3
  2. A followup question to question #1

Next Lesson >>

Back to Schedule

Reuse

CC-BY-4.0