List of Topics:
Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Do Boolean Indexing, Fancy Indexing and Subsetting of an Array Using NumPy

NumPy Indexing

Condition for Boolean Indexing, Fancy Indexing, and Subsetting

  • Description:
    In NumPy, Boolean indexing, fancy indexing, and subsetting are essential techniques to manipulate data in arrays:

    Boolean Indexing: Filters elements of an array based on a condition (True/False mask).
    Fancy Indexing: Uses an array of indices to access specific elements of an array.
    Subsetting: Refers to selecting specific parts of an array using slicing or advanced indexing techniques.
Step-by-Step Process
  • Import NumPy:
    Import the NumPy library using import numpy as np.
  • Create a NumPy Array:
    Create an array using np.array().
  • Boolean Indexing:
    Apply a condition on the array to filter elements, such as arr > 5.
  • Fancy Indexing:
    Select elements using an array of indices or multi-dimensional indexing.
  • Subsetting:
    Use slicing (:) to extract specific rows, columns, or subarrays from the array.
Sample Source Code
  • # Code for Boolean Indexing, Fancy Indexing, and Subsetting

    import numpy as np

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

    # Boolean Indexing
    boolean_mask = arr > 5
    print("Boolean Indexing (Elements greater than 5):")
    print(arr[boolean_mask])

    # Fancy Indexing
    indices = [1, 3, 5, 7]
    fancy_result = arr[indices]
    print("\nFancy Indexing (Elements at indices 1, 3, 5, 7):")
    print(fancy_result)

    # Subsetting (Slicing)
    subset_result = arr[2:6]
    print("\nSubsetting (Elements from index 2 to 6):")
    print(subset_result)

Screenshots
  • NumPy Indexing Output