Access & Modify NumPy Using Tuple indexing in Python

In this tutorial, you’ll learn how to use tuple indexing to not only access but also modify elements within NumPy arrays.

Whether you’re updating single elements or modifying slices, tuple indexing will enhance your data manipulation capabilities.

 

 

Tuple Indexing in NumPy: Accessing Elements

Tuple indexing using the syntax arr[(x, y)] is used for extracting specific elements from a multidimensional array.

import numpy as np
signal_strengths = np.array([
    [12, 15, 17],
    [22, 25, 27],
    [32, 35, 37]
])
specific_strength = signal_strengths[(1, 2)]
print(specific_strength)

Output:

27

Here, 27 is at the second location and the third time interval.

 

Indexing with an Array of Tuples

Here’s an example to show how you can use an array of tuples for indexing:

import numpy as np
signal_strengths = np.array([
    [12, 15, 17, 19],
    [22, 25, 27, 29],
    [32, 35, 37, 39],
    [42, 45, 47, 49]
])
indices = np.array([(0, 1), (2, 3), (3, 0)])
selected_strengths = signal_strengths[indices[:, 0], indices[:, 1]]
print("Selected Strengths:", selected_strengths)

Output:

Selected Strengths: [15 39 42]

In this example:

  • indices is an array of tuples, each specifying a location-time pair.
  • The expression signal_strengths[indices[:, 0], indices[:, 1]] retrieves signal strengths at these specific pairs.
  • The output Selected Strengths: [15 39 42] corresponds to the strengths at the specified indices.

 

Boolean Indexing with Tuples

We can use a combination of boolean conditions and tuple indexing to select data:

import numpy as np
signal_strengths = np.array([
    [12, 15, 17, 19],
    [22, 25, 27, 29],
    [32, 35, 37, 39],
    [42, 45, 47, 49]
])
condition = signal_strengths > 30
selected_strengths = signal_strengths[np.nonzero(condition)]
print("Selected Strengths:", selected_strengths)

Output:

Selected Strengths: [32 35 37 39 42 45 47 49]

In this corrected approach:

  • The condition generates a boolean array to make elements greater than 30.
  • np.nonzero(condition) returns a tuple of arrays, each containing the indices of elements that meet the condition.
  • selected_strengths are the values in signal_strengths that satisfy our condition.

 

Modifying Array Elements Using Tuple Indexing

Let’s look at an example of updating single elements in a dataset:

import numpy as np
signal_strengths = np.array([
    [12, 15, 17],
    [22, 25, 27],
    [32, 35, 37]
])
signal_strengths[(1, 2)] = 30
print("Updated Array:\n", signal_strengths)

Output:

Updated Array:
 [[12 15 17]
 [22 25 30]
 [32 35 37]]

In this example, we updated the signal strength at the second location and third time interval to 30.

The tuple (1, 2) targeted the element to be updated.

Leave a Reply

Your email address will not be published. Required fields are marked *