Saturday 6 April 2024

Indexing and slicing for 1D NumPy arrays with illustrative examples.

 Indexing and slicing for 1D NumPy arrays with illustrative examples.


  • 1D Arrays: Think of 1D arrays as simple lists of numbers.

  • Zero-Based Indexing: The first element has an index of 0, the second has an index of 1, and so on.

Example Array


import numpy as np

arr = np.array([10, 5, -3, 8, 2])
print(arr)  # Output: [10  5 -3  8  2]

Indexing (Accessing Elements)

  • Syntax: array_name[index]

  • Examples:

  • first_element = arr[0] (Accesses the value 10)

  • third_element = arr[2] (Accesses the value -3)


  • Syntax: array_name[start:end:step]

  • start: Starting index (inclusive)

  • end: Ending index (exclusive)

  • step: Step size between included elements

  • Examples:

  • sub_arr = arr[1:4] # Elements from index 1 to 3 (Output: [5 -3 8])

  • every_other = arr[::2] # Every other element (Output: [10 -3 2])

  • reversed_arr = arr[::-1] # Reverse the array (Output: [ 2 8 -3 5 10])

Additional Examples

  • Last Element
    last_element = arr[-1]

  • Last Three Elements:
    last_three = arr[-3:]

Key Notes

  • Negative Indexing: Using negative indices starts counting from the end of the array.

  • Modifying Through Slices: Changes you make to a slice of a NumPy array are reflected in the original array.

Important: Slices and Copies

If you need an independent copy of a portion of the array, use the .copy() method explicitly.


modified_slice = arr[1:3].copy()  # Creates a separate copy
modified_slice[0] = 100               # Doesn't change the original 'arr'


how to extract the first three elements from a NumPy array:

Using Slicing:


import numpy as np

arr = np.array([10, 5, -3, 8, 2])

first_three = arr[:3# Slice from the beginning (index 0) up to index 3 (exclusive)
print(first_three)  # Output: [10  5 -3]


  • : before index 3: Implies taking elements from the start of the array.

  • Index 3 is not included: Slicing in Python goes up to but does not include the ending index.

 how you would select the middle element of a NumPy array if it has an odd number of elements:


import numpy as np

def get_middle_element(arr):
    if len(arr) % 2 == 0# Check if the array length is even
        print("Array has an even number of elements, no single middle element.")
        return None 

    middle_index = len(arr) // 2  # Integer division to find the middle index
    middle_element = arr[middle_index]
    return middle_element

# Example with an odd-length array
odd_array = np.array([5, 2, 9, -1, 4])

middle = get_middle_element(odd_array)
print(middle)  # Output: 9


  1. Function for Flexibility: The code is encapsulated in a function get_middle_element() for reusability.

  2. Even Check: First, we check if the array length is even. If so, it has no single, well-defined middle element.

  3. Middle Index: If the array is odd-length, we use integer division (//) to find the middle index directly.

  4. Element Access: The middle element is accessed using its index.

Let's Test It!


even_array = np.array([1, 3, 6, 2])
get_middle_element(even_array)  # Output: "Array has an even number of elements..."

how to replace the first two elements of a NumPy array with zeros:

Using Slicing and Assignment


import numpy as np

arr = np.array([10, 5, -3, 8, 2])

arr[:2] = 0  # Assign zero to the slice containing the first two elements
print(arr)  # Output: [0 0 -3  8  2]


  1. Slicing: arr[:2] selects the first two elements of the array.

  2. Assignment: We assign the value 0 to the selected slice. NumPy efficiently broadcasts this zero value to replace both elements within the slice.

Key Point: Modifying Slices

In NumPy, slices often act as views into the original array. This means changing a slice also modifies the corresponding elements in the original array.

Let's Experiment!

Here are a few variations to try:

  • Replace last three elements with 1
    arr[-3:] = 1

  • Replace every other element starting from the first one with -1
    arr[::2] = -1

Let me know if you have any specific replacement patterns in mind, and I'll gladly help you implement them in NumPy!

No comments:

Post a Comment

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