📊

Managing Arrays in Python with NumPy

Sep 25, 2024

Notes on Managing Arrays in Python (Module 3)

Introduction

  • Current focus: Managing arrays in Python using two modules: array module and numpy module.
  • Discussion on numpy module includes:
    • Installation and usage
    • Creation of arrays
    • Dimensions of arrays (0D, 1D, 2D, 3D)
    • Initialization methods (ones, zeros, random numbers)

Array Indexing

  • Accessing array elements by referring to their index number.
  • Familiarity with indexing from languages like C, C++, Java.
  • Dimensional Indexing:
    • 1D array -> 1 index
    • 2D array -> 2 indices (rows and columns)
    • 3D array -> 3 indices (3 axes: axis 0, axis 1, axis 2)

Example of 3D Array Indexing

  • Coordinate (1, 1, 1) refers to the second row, second column, and second depth in 3D array.
    • Accessing value parallel to a specific point (e.g., value 4).

Negative Indexing

  • Can be used to access elements from the end of an array.
  • Familiarity with negative indexing from lists.

Examples of Negative Indexing

  • For a 2D array (AR):
    • AR[0, -1] -> last element of the first row (value 5).
    • AR[-1, 2] -> third element from the last row.
    • AR[-1, -1] -> last element from the last row (value 15).
  • General summary of negative indexing use cases.

Array Slicing

  • Slicing: Accessing elements between given start and end indices.
  • Specify start index, end index, and optionally a step value.
    • Default start index is 0, default end index is the length of the array, default step is 1.

Examples of Slicing

  • data[0] -> first element.
  • data[0:2] -> elements at index 0 and 1 (index 2 is excluded).
  • Negative slicing examples (e.g., data[-3:-1]).

Slicing in 2D Arrays

  • Syntax for slicing in 2D arrays includes specifying both row and column indices.
  • Example slicing outputs to observe values from specific rows and columns.

Numpy Array Properties and Methods

  • dtype property: Returns the data type of the array.
  • astype method: Creates a copy of the array with a specified data type.
    • Example: Converting float array to integer array.

Methods for Data Type Operations

  • Example showing how to convert string values to float and integers.

Copy vs View Methods in Numpy

  • Copy Method: Creates a new array. Changes to copy do not affect the original array.
  • View Method: Creates a reference to the original array. Changes affect both the original and the view.

Examples

  • Example showing differences between using copy and view methods.
    • Modifications in the copy do not change the original.
    • Modifications in the view reflect in the original.

Conclusion

  • Next session will cover array shape and reshape.
  • Encouragement to review session material.