NumPy is the foundation underneath much of the Python data stack. pandas is built on top of it, so learning NumPy helps you understand why pandas is fast with numeric data.
In this tutorial, you will:
- import NumPy
- create NumPy arrays
- inspect array shape and data type
- perform vectorised calculations
- select and filter array values
- create simple 2D arrays
- connect NumPy arrays back to pandas
Before starting:
- Open the
session7folder in Visual Studio Code. - Activate your virtual environment.
- Confirm dependencies are installed:
pip install -r requirements.txt- Create your exercise file:
session7/solutions/exercise-07-03.pyNumPy: a Python library for fast numeric arrays.array: a collection of values with the same general data type.shape: the size of an array in each dimension.dtype: the data type stored in an array.vectorised operation: an operation applied to many values at once.boolean mask: a True/False array used to filter values.2D array: a table-like array with rows and columns.
Most Python code imports NumPy using the alias np.
File: session7/solutions/exercise-07-03.py
import numpy as np
print(np.__version__)Create a simple array from a Python list.
File: session7/solutions/exercise-07-03.py
import numpy as np
scores = np.array([72, 85, 91, 64, 78])
print(scores)
print(type(scores))Arrays have a shape and a data type.
File: session7/solutions/exercise-07-03.py
import numpy as np
scores = np.array([72, 85, 91, 64, 78])
print(scores.shape)
print(scores.dtype)Note
For a one-dimensional array, the shape shows how many values are in the array.
NumPy can calculate common statistics.
File: session7/solutions/exercise-07-03.py
import numpy as np
scores = np.array([72, 85, 91, 64, 78])
print(np.mean(scores))
print(np.min(scores))
print(np.max(scores))
print(np.std(scores))With NumPy, you can apply a calculation to the whole array at once.
File: session7/solutions/exercise-07-03.py
import numpy as np
scores = np.array([72, 85, 91, 64, 78])
scores_plus_5 = scores + 5
print(scores_plus_5)This is shorter and usually faster than writing a loop.
Create a True/False mask, then use it to filter values.
File: session7/solutions/exercise-07-03.py
import numpy as np
scores = np.array([72, 85, 91, 64, 78])
mask = scores >= 80
print(mask)
print(scores[mask])Use arange() to create regular numeric sequences.
File: session7/solutions/exercise-07-03.py
import numpy as np
numbers = np.arange(1, 11)
print(numbers)
print(numbers * 2)A 2D array is useful for matrix-style data.
File: session7/solutions/exercise-07-03.py
import numpy as np
matrix = np.array([
[10, 20, 30],
[40, 50, 60],
])
print(matrix)
print(matrix.shape)Use row and column indexes to select values from a 2D array.
File: session7/solutions/exercise-07-03.py
import numpy as np
matrix = np.array([
[10, 20, 30],
[40, 50, 60],
])
print(matrix[0, 0])
print(matrix[0, :])
print(matrix[:, 1])Tip
matrix[0, :] means row 0 and all columns.
matrix[:, 1] means all rows and column 1.
You can convert a pandas column to a NumPy array.
File: session7/solutions/exercise-07-03.py
import numpy as np
import pandas as pd
pokemon = pd.read_csv("datasets/Pokemon.csv", encoding="cp1252")
attack_values = pokemon["Attack"].to_numpy()
print(attack_values[:10])
print(np.mean(attack_values))Add your answers to:
session7/solutions/exercise-07-03.pyTasks:
- Import NumPy as
np. - Create an array called
scoreswith at least 8 numeric values. - Print the array, shape, and data type.
- Print the mean, minimum, maximum, and standard deviation.
- Create a new array called
scores_plus_10, then filter and print only scores greater than or equal to80. - Create an array with numbers from
1to20, then print only the even numbers. - Create a 3 by 3 matrix, print its shape, print the first row, and print the second column.
- Load
Pokemon.csvwith pandas, convert theAttackcolumn to a NumPy array, print the average attack, print attack values greater than or equal to120, and add a short comment explaining one difference between a Python list and a NumPy array.
Complete the following quiz.
quizmd quizzes/python-session-07-part-03-quiz.mdIf you want to choose a theme:
quizmd --theme light quizzes/python-session-07-part-03-quiz.md
quizmd --theme dark quizzes/python-session-07-part-03-quiz.mdYou are now ready for the homework or class challenge.