- Lab
- Data

Accessing Arrays with NumPy Hands-on Practice
This lab provides an evironment to practice Array creation, manipulation and access via NumPy's built-in functionality. It covers creating, accessing, indexing, broadcasting, and iterating with numpy 1D and 2D arrays.

Path Info
Table of Contents
-
Challenge
Getting Started with NumPy Arrays
Jupyter Guide
To get started, open the file on the right entitled "Step 1...". You'll complete each task for Step 1 in that Jupyter Notebook file. Remember, you must run the cells
(ctrl/cmd + Enter)
for each task before moving onto the next task in the Jupyter Notebook. Continue until you have completed all tasks in this step. Then when you are ready to move onto the next step, you'll come back and click on the file for the next step until you have completed all tasks in all steps of the lab.
Getting Started with NumPy Arrays
To review the concepts covered in this step, please refer to the Creating and Accessing Arrays module of the Accessing Arrays with NumPy course.
Understanding NumPy arrays is important because they provide a more efficient and versatile way to handle data in Python. They allow for faster computations and more advanced operations compared to standard Python lists or tuples.
In this step, we will dive into the world of NumPy arrays. Our goal is to understand how they differ from standard Python data structures and how to create them. We will use the
numpy.array()
function to create one-dimensional and multi-dimensional arrays from Python lists. We will also explore thedtype
argument to specify the data type of the elements in the array.
Task 1.1: Importing NumPy
Before we can start working with NumPy, we need to import the library. The convention is to import NumPy with an alias,
np
.π Hint
Imports are case sensitive, and to import NumPy, you must use the all lowercase spelling
numpy
.Importing syntax looks like:
import module as alias
π Solution
# Import libraries import numpy as np
Task 1.2: Creating a One-Dimensional NumPy Array
Create a 1D NumPy array from a Python list. The list should contain the numbers
1
through5
. Display the results.π Hint
You can create a numpy array from a list by passing the list directly into the
np.array()
function.π Solution
# Create a 1D numpy array arr = np.array([1, 2, 3, 4, 5]) arr
Task 1.3: Creating a Multi-Dimensional NumPy Array
Create a 2D
NumPy
array from a Python list. The list should contain two sublists, the first containing the numbers1
through3
and the second containing4
through6
. Display the results.π Hint
You can use the
np.array()
function with the the python list as the argument. To get a 2-D array, use a nested list:list_2d = [[1],[2]]
Note: the two 'sublists' must be of the same length.
π Solution
# Create a 2D numpy array arr_2d = np.array([[1, 2, 3], [4, 5, 6]]) arr_2d
Task 1.4: Specifying the Data Type of a NumPy Array
Create a NumPy array with the numbers
1
through5
, but specify the data type of the elements to befloat
. Display the results. Notice the difference fromTask 1.2
: the numbers in the array should now be represented as floating point numbers as opposed to integers.π Hint
Copy your code from task 1.2 and add the dtype argument to the array function.
π Solution
# Specify the data type arr_float = np.array([1, 2, 3, 4, 5], dtype=float) arr_float
-
Challenge
Creating and Accessing NumPy Arrays
Creating and Accessing NumPy Arrays
To review the concepts covered in this step, please refer to the Creating and Accessing Arrays module of the Accessing Arrays with NumPy course.
Creating and accessing NumPy arrays is important because it forms the basis for any operation we want to perform on the data. Understanding how to index and slice arrays allows us to access and manipulate specific parts of the data.
In this step, we will focus on creating and accessing NumPy arrays. We will use the
numpy.arange()
andnumpy.linspace()
functions to generate 1D arrays, and thenumpy.diag()
andnumpy.eye()
functions to generate 2D arrays. We will also learn how to index and slice arrays to access specific elements or sections of the array. Sure, here's the updated content with a more detailed hint for each task and the first task now focused on importingnumpy
.
Task 2.1: Importing NumPy
Import the NumPy library using the standard alias
np
.π Hint
Use the
import
keyword followed bynumpy
and thenas
to set the standard alias.π Solution
import numpy as np
Task 2.2: Creating a 1D array using
np.arange()
Create a 1D array of integers from
0
to9
using thenp.arange()
function. Display the array.π Hint
Use
np.arange(start, stop)
wherestart
is inclusive andstop
is exclusive. Here, you want to start at0
and stop just before10
. If only one number is passed tonp.arange
, start will default to 0.π Solution
# Assuming numpy has been imported as np array_1d = np.arange(10) array_1d
Task 2.3: Creating a 1D array using
np.linspace()
Create a 1D array of 5 evenly spaced numbers between 0 and 1 using the
np.linspace()
function. Display the array.π Hint
The
np.linspace(start, stop, num)
function creates an array withnum
numbers, evenly spaced betweenstart
andstop
, including both endpoints.π Solution
# Assuming numpy has been imported as np array_linspace = np.linspace(0, 1, 5) array_linspace
Task 2.4: Creating a 2D array using
np.diag()
Create a 2D array with the numbers 1, 2, 3, 4 on the diagonal using the
np.diag()
function. Display it.π Hint
To place numbers on the diagonal, pass a one-dimensional array to
np.diag()
. The function will fill the diagonal of a 2D array with these numbers.π Solution
# Assuming numpy has been imported as np array_diag = np.diag([1, 2, 3, 4]) array_diag
Task 2.5: Creating a 2D array using
np.eye()
Create a 2D array with ones on the diagonal and zeros elsewhere using the
np.eye()
function. Display it.π Hint
The
np.eye(N)
function creates an N x N identity matrix, which is a 2D array with ones on the main diagonal and zeros elsewhere.π Solution
# Assuming numpy has been imported as np array_eye = np.eye(4) array_eye
Task 2.6: Accessing elements of a 1D array
Access the 5th element of the 1D array created using the
np.arange()
function inTask 2.2
. Display it.π Hint
Array indexing is zero-based, so the 5th element is at index 4. Use square brackets to access the element:
array[index]
.π Solution
# Assuming numpy has been imported as np and array_1d is defined fifth_element = array_1d[4] fifth_element
Task 2.7: Slicing a 1D array
Slice the 1D array created using the
np.arange()
function inTask 2.2
to get the 3rd, 4th, 5th, and 6th elements. Display them.π Hint
Use the slice notation
array[start:stop]
, wherestart
is the index of the first element you want (inclusive) andstop
is the index of the element just after the last one you want (exclusive). In this case, you start at index 2 and stop at index 6. Don't forget that array indexing starts at 0, so the 6th element will be in index 5.π Solution
# Assuming numpy has been imported as np and array_1d is defined sliced_array = array_1d[2:7] sliced_array
Task 2.8: Accessing elements of a 2D array
Given a 2D array created using the
np.eye()
function inTask 2.5
, access the element in the second row and third column. Display it.π Hint
Remember that NumPy arrays are zero-indexed. To access the element at the second row and third column, you would use the indices
[1, 2]
.π Solution
# Assuming numpy has been imported as np and array_eye is defined element_2d = array_eye[1, 2] element_2d
-
Challenge
Advanced Array Indexing
Advanced Array Indexing
To review the concepts covered in this step, please refer to the Advanced Array Indexing Routines module of the Accessing Arrays with NumPy course.
Advanced array indexing is important because it provides more flexibility and control over the data. It allows us to select multiple elements, reshape the array, and even filter elements based on certain conditions.
In this step, we will delve into advanced array indexing techniques. We will learn how to select multiple elements using a list of indices, perform Boolean indexing, and reshape arrays using the
reshape()
method. We will also learn how to flatten a multi-dimensional array into a one-dimensional array.
Task 3.1: Creating an Initial 2D Array of Numeric Data
Create a 2D array of numeric data with at least
3
rows and3
columns. Let's call this arraydata_matrix
. There should be at least one number greater50
and one less than50
in your array. Display the array.π Hint
To create a 2D array, you can use the
np.array()
function and pass a list of lists, where each inner list represents a row.π Solution
# Create a 2D array of numeric data data_matrix = np.array([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) # Display the data_matrix data_matrix
Task 3.2: Selecting Multiple Elements Using a List of Indices
Select multiple elements from the
data_matrix
using a list of row and column indices. For this task, select elements at positions(0, 2)
,(1, 1)
, and(2, 0)
. Display the results.π Hint
To select multiple elements from a 2D array, you can use the method of passing two arrays to the indexing operator
[]
: one for the rows and one for the columns.π Solution
# Assume data_matrix is already defined as a 2D array from the previous task # Select elements at positions (0, 2), (1, 1), and (2, 0) selected_elements = data_matrix[[0, 1, 2], [2, 1, 0]] # Display the selected elements selected_elements
Task 3.3: Performing Boolean Indexing
Perform
Boolean indexing
to select all elements fromdata_matrix
that are greater than 50. Print the boolean index as well as the results of the array indexed with the boolean index.π Hint
To perform Boolean indexing, you can use a condition directly on the array, which will return a Boolean array that can be used to index the original array.
π Solution
# Assume data_matrix is already defined as a 2D array from previous tasks # Perform Boolean indexing to select all elements greater than 50 greater_than_fifty = data_matrix[data_matrix > 50] # Display the boolean mask print(data_matrix>50) # Display the elements greater than 50 greater_than_fifty
Task 3.4: Reshaping Arrays
Reshape the
data_matrix
into a 2D array with1
row. Store the result in a variable namedsingle_row_matrix
. Display the results.π Hint
To reshape an array into a single row, you can use the
reshape()
method with-1
as the number of columns, which tells NumPy to calculate the number of columns automatically.π Solution
# Assume data_matrix is already defined as a 2D array from previous tasks # Reshape the data_matrix into a 2D array with 1 row single_row_matrix = data_matrix.reshape((1, -1)) # Display the reshaped single row matrix single_row_matrix
Task 3.5: Flattening a Multi-dimensional Array
Flatten the
data_matrix
into a 1D array. Store the result in a variable namedflattened_data
. Display the results. Compare your result to theTask 3.4
. Notice the extra dimension in the array displayed fromTask 3.4
.π Hint
To flatten a multi-dimensional array into a 1D array, you can use the
ravel()
method or thereshape()
method with-1
as an argument.π Solution
# Assume data_matrix is already defined as a 2D array from previous tasks # Flatten the data_matrix into a 1D array flattened_data = data_matrix.ravel() # Display the flattened data flattened_data
-
Challenge
Broadcasting in NumPy
Broadcasting in NumPy
To review the concepts covered in this step, please refer to the Broadcasting module of the Accessing Arrays with NumPy course.
Broadcasting is important because it allows us to perform operations on arrays of different shapes. This is a powerful feature that makes NumPy a versatile tool for data manipulation and computation.
In this step, we will explore broadcasting in NumPy. We will learn how NumPy compares the shapes of two arrays to determine if they are compatible for broadcasting. We will also perform computations on arrays with different shapes using NumPy's broadcasting feature.
Task 4.1: Importing NumPy
First, we need to import the
NumPy
library to use its functions.π Hint
Use the
import
keyword to import NumPy. Remember to use the aliasnp
for convenience.π Solution
import numpy as np
Task 4.2: Creating Arrays
Create two NumPy arrays of different shapes. One array should be
1-dimensional
with three elements and the other should be2-dimensional
with 2 rows and 3 columns. Display the results.π Hint
Use the
np.array()
function to create arrays. For the 2D array, you can pass a list of lists to the function.π Solution
array1 = np.array([1, 2, 3]) array2 = np.array([[1, 2, 3], [4, 5, 6]]) print(array1) print(array2)
Task 4.3: Understanding Broadcasting
Perform an operation (like
addition
) on the two arrays you created. Observe the result and try to get a feel for how broadcasting works.π Hint
You can perform an operation on the arrays just like you would with regular numbers. For example,
array1 + array2
.π Solution
result = array1 + array2 print(result) result = array1 * array2 print(result)
Task 4.4: Broadcasting with Different Shapes
Create two new arrays of different shapes that are not compatible for broadcasting. Try to perform an operation on these arrays and observe the error message.
π Hint
For the arrays to be incompatible for broadcasting, they need to have different shapes and the dimensions should not be equal to 1. For example, a 2x3 array and a 3x2 array are not compatible for broadcasting. Check out the broadcasting rules here:
-
Dimension Alignment: For arrays with a different number of dimensions, prepend 1s to the dimensions of the smaller array until both arrays have the same number of dimensions. (e.g.
arr_3x2
andarr_2
will add1
dimension to the second array to make itarr_1x2
) -
Size Adjustment: Compare the size of each dimension. If an array has a size of 1 in a particular dimension, it can be expanded to match the other array's size in that dimension. A size mismatch in any dimension where neither size is 1 means the arrays are not compatible for broadcasting.
-
Broadcasting Failure: If, after dimension alignment and size adjustment, there is any dimension where the sizes are different and neither is 1, broadcasting is not possible, and an error is raised.
This is a tough concept, so play around and try to get a feel for it.
π Solution
array3 = np.array([[1, 2, 3], [4, 5, 6]]) array4 = np.array([[1, 2], [3, 4], [5, 6]]) try: result = array3 + array4 except ValueError as e: print(e)
-
-
Challenge
Iterating over NumPy Arrays
Iterating over NumPy Arrays
To review the concepts covered in this step, please refer to the Iterating over NumPy Arrays module of the Accessing Arrays with NumPy course.
In this step, we'll focus on a crucial skill for data practicioners: iterating through NumPy arrays. It's a fundamental technique that enables efficient data access and manipulation. Let's dive right in!
Task 5.1: Importing NumPy
Before we can start working with NumPy arrays, we need to import the NumPy library. Import the NumPy library as
np
.π Hint
Use the
import
keyword followed by the library name andas
keyword to give it a short alias. For example,import numpy as np
.π Solution
import numpy as np
Task 5.2: Creating a NumPy Array
Create a 1D NumPy array named
arr
with the values from 1 to 5.π Hint
Use the
np.array()
function to create a NumPy array. Pass a list of values as the argument. For example,np.array([1, 2, 3, 4, 5])
.π Solution
arr = np.array([1, 2, 3, 4, 5])
Task 5.3: Iterating Over a 1D Array
Iterate over the
arr
array using afor
loop and print each element.π Hint
Use a
for
loop to iterate over the array. For example,for i in arr: print(i)
.π Solution
for i in arr: print(i)
Task 5.4: Creating a 2D Array
Create a 2D NumPy array named
arr_2d
with the values from 1 to 9 reshaped into a 3x3 matrix.π Hint
Use the
np.arange
function to create a 1D NumPy array and thereshape()
method to reshape it into a 3x3 matrix. For example,np.arange(1,5).reshape(2, 2)
.π Solution
arr_2d = np.arange(1,10).reshape(3, 3)
Task 5.5: Iterating Over a 2D Array (Double For Loop)
Iterate over the
arr_2d
array using a doublefor
loop to print each element.π Hint
Use two nested
for
loops to iterate over both dimensions of the array. For example, use a loop to iterate over rows and another loop to iterate over each element in the row.π Solution
for row in arr_2d: for element in row: print(element)
What's a lab?
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Provided environment for hands-on practice
We will provide the credentials and environment necessary for you to practice right within your browser.
Guided walkthrough
Follow along with the authorβs guided walkthrough and build something new in your provided environment!
Did you know?
On average, you retain 75% more of your learning if you get time for practice.