Hamburger Icon
  • Labs icon Lab
  • Data
Labs

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.

Labs

Path Info

Level
Clock icon Beginner
Duration
Clock icon 39m
Published
Clock icon Dec 06, 2023

Contact sales

By filling out this form and clicking submit, you acknowledge ourΒ privacy policy.

Table of Contents

  1. 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 the dtype 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 through 5. 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 numbers 1 through 3 and the second containing 4 through 6. 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 through 5, but specify the data type of the elements to be float. Display the results. Notice the difference from Task 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
    
  2. 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() and numpy.linspace() functions to generate 1D arrays, and the numpy.diag() and numpy.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 importing numpy.


    Task 2.1: Importing NumPy

    Import the NumPy library using the standard alias np.

    πŸ” Hint

    Use the import keyword followed by numpy and then as 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 to 9 using the np.arange() function. Display the array.

    πŸ” Hint

    Use np.arange(start, stop) where start is inclusive and stop is exclusive. Here, you want to start at 0 and stop just before 10. If only one number is passed to np.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 with num numbers, evenly spaced between start and stop, 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 in Task 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 in Task 2.2 to get the 3rd, 4th, 5th, and 6th elements. Display them.

    πŸ” Hint

    Use the slice notation array[start:stop], where start is the index of the first element you want (inclusive) and stop 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 in Task 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
    
  3. 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 and 3 columns. Let's call this array data_matrix. There should be at least one number greater 50 and one less than 50 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 from data_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 with 1 row. Store the result in a variable named single_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 named flattened_data. Display the results. Compare your result to the Task 3.4. Notice the extra dimension in the array displayed from Task 3.4.

    πŸ” Hint

    To flatten a multi-dimensional array into a 1D array, you can use the ravel() method or the reshape() 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
    

  4. 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 alias np 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 be 2-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 and arr_2 will add 1 dimension to the second array to make it arr_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)
    
  5. 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 and as 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 a for 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 the reshape() 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 double for 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.