Skip to Content

NumPy Indexing

Indexing in NumPy allows you to access and manipulate elements in arrays. Beyond basic indexing, NumPy offers advanced techniques like fancy indexing, boolean indexing, and conditional operations, which provide powerful tools for data selection and manipulation.


Fancy Indexing

Fancy indexing lets you use arrays of integers or boolean values to access specific elements in another array. This method is particularly useful for non-contiguous data selection.

Examples

import numpy as np # Create an array array = np.array([10, 20, 30, 40, 50]) # Select elements at indices 0, 2, and 4 selected = array[[0, 2, 4]] print("Selected elements:", selected) # Output: [10 30 50] # 2D fancy indexing array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) selected_2d = array_2d[[0, 1], [1, 2]] print("Selected elements from 2D array:", selected_2d) # Output: [2 6]

Boolean Indexing

Boolean indexing allows you to filter elements based on conditions. It returns an array with only the elements that satisfy the condition.

Examples

# Create an array array = np.array([1, 2, 3, 4, 5]) # Select elements greater than 3 filtered = array[array > 3] print("Elements greater than 3:", filtered) # Output: [4 5] # Use multiple conditions filtered_multiple = array[(array > 2) & (array < 5)] print("Elements between 2 and 5:", filtered_multiple) # Output: [3 4]

Conditional Operations

Conditional operations allow you to apply conditions and modify elements in an array based on those conditions.

Examples

# Create an array array = np.array([10, 15, 20, 25, 30]) # Set all elements greater than 20 to 0 array[array > 20] = 0 print("Modified array:", array) # Output: [10 15 20 0 0] # Apply a condition with a function modified = np.where(array < 20, array * 2, array) print("Array after applying np.where:", modified) # Output: [20 30 20 0 0]

Try It Yourself

Problem 1: Fancy Indexing

Create an array with numbers from 10 to 50 (step of 10). Use fancy indexing to select the first, third, and fifth elements.

Show Code

import numpy as np # Create an array array = np.array([10, 20, 30, 40, 50]) # Select elements selected = array[[0, 2, 4]] print("Selected elements:", selected)

Problem 2: Boolean Indexing

Create an array of integers from 1 to 10. Use boolean indexing to select even numbers only.

Show Code

import numpy as np # Create an array array = np.arange(1, 11) # Select even numbers evens = array[array % 2 == 0] print("Even numbers:", evens)

Problem 3: Conditional Operations

Create a 1D array with values from 5 to 15. Replace all values less than 10 with -1 using a conditional operation.

Show Code

import numpy as np # Create an array array = np.arange(5, 16) # Apply condition array[array < 10] = -1 print("Modified array:", array)

Pyground

Play with Python!

Output:

Last updated on