Translate

Tuesday 2 April 2024

NumPy arrays through indexing and slicing.

 


Ways to access and manipulate elements within NumPy arrays through indexing and slicing.

Fundamentals

  • Zero-Based Indexing: Like Python lists, NumPy array indexing starts from 0. The first element is at index 0, the second at index 1, and so on.

  • Multidimensional Arrays: Indexing becomes more interesting with multiple dimensions (matrices, tensors).

Accessing Elements

  1. Single Element:

  • For a 1D Array: array_name[index]
    Python
    arr = np.array([5, 10, -2, 6])
    first_element = arr[0]   # Accesses the value 5

  • For a 2D array (matrix): array_name[row_index, column_index]
    Python
    matrix = np.array([[1, 2, 3], [4, 5, 6]])
    element_at_0_1 = matrix[0, 1# Accesses the value 2 (zero-based)

Slicing

Slicing extracts sub-arrays using the following syntax: array_name[start:end:step]

  • start: Index of the first element to include (inclusive)

  • end: Index where the slice ends (exclusive)

  • step: The step size between elements to include

Examples:


Python


import numpy as np

arr = np.arange(12)
print(arr)                 # [ 0  1  2  3  4  5  6  7  8  9 10 11]

# Get elements from index 2 to 6 (exclusive)
sub_arr = arr[2:6]     # [ 2  3  4  5]

# Every other element
every_other = arr[::2# [ 0  2  4  6  8 10]

# Reverse the array
reversed_arr = arr[::-1# [11 10  9  8  7  6  5  4  3  2  1  0]

Slicing Multidimensional Arrays

  • Each dimension: Separate slice operations with commas.

  • Colon for all elements: A colon in a dimension means "take all elements along that dimension.


Python


matrix = np.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])

# First row
first_row = matrix[0, :]

# Second column
second_col = matrix[:, 1

# Top-left 2x2 sub-matrix
top_left_corner = matrix[:2, :2]

Important Notes:

  • Modifying Slices: Modifying a slice obtained from NumPy arrays also modifies the original array. This happens because slices are often views into the original data.

  • Copy if Needed: If you want to work with a separate copy, explicitly make a copy of the slice using .copy().


Assignments to practice NumPy indexing and slicing, along with solutions.

Assignment 1: Basic Slicing

  • Instructions: Given the following array,
    Python
    import numpy as np
    data = np.arange(1, 21).reshape(4, 5)

  • Extract the elements in the second row.

  • Extract the elements from the second column to the end.

  • Create a sub-array containing the bottom-right 2x2 corner.

  • Select every other element from the first and third rows.

  • Solution:
    Python
    # Second row
    second_row = data[1, :]

    # Second column to end
    second_col_onwards = data[:, 1:]

    # Bottom-right corner
    bottom_right = data[2:, 3:]

    # Every other element, first and third rows
    select_elements = data[[0, 2], ::2]

Assignment 2: Calculation with Slices

  • Instructions: Consider the following array:
    Python
    temperatures = np.array([16, 25, -2, 19, 21])

  • Calculate the average of the positive temperatures.

  • Select temperatures below the freezing point of water (0 degrees Celsius) and replace them with 0.

  • Solution:
    Python
    # Average of positive temperatures
    positive_temps = temperatures[temperatures > 0]
    average_positive = np.mean(positive_temps)

    # Handling subzero temperatures
    temperatures[temperatures < 0] = 0

Assignment 3: Matrix Manipulation

  • Instructions: Given a matrix:
    Python
    matrix = np.array([[10, 5, -1],
                      [3, 8, 2],
                      [6, -4, 9]])

  • Reverse the order of the columns.

  • Swap the first and last rows.

  • Extract the values in the diagonal (top-left to bottom-right).

  • Solution
    Python
    # Reverse columns
    reversed_cols = matrix[:, ::-1]

    # Swap rows
    matrix[[0, 2], :] = matrix[[2, 0], :] 

    # Extract diagonal elements
    diagonal_elements = matrix.diagonal()

Tips

  • Experiment: Try different variations of slicing to solidify your understanding.

  • Visualization: For matrices, print arrays before and after manipulation to visually confirm your results.

Enhancements

  • Work with larger datasets.

  • Combine indexing with NumPy functions like np.max(), np.where(), etc.

Let me know if you want to tackle more challenging assignments, explore advanced indexing like boolean masking, or work with real-world datasets!


No comments:

Post a Comment

Note: only a member of this blog may post a comment.