Python > Working with Data > Numerical Computing with NumPy > Indexing and Slicing
Basic NumPy Indexing and Slicing
This snippet demonstrates fundamental indexing and slicing techniques using NumPy arrays, including accessing single elements, extracting subarrays, and using boolean indexing.
Creating a NumPy Array
First, we import the NumPy library. Then, we create a one-dimensional NumPy array named arr
containing numbers from 0 to 9 using np.arange(10)
. Finally, we print the array to display its contents.
import numpy as np
arr = np.arange(10)
print(arr)
Accessing Single Elements
NumPy arrays can be accessed using their index. arr[0]
retrieves the element at index 0 (the first element). arr[5]
retrieves the element at index 5. Negative indices can be used to access elements from the end of the array; arr[-1]
accesses the last element.
print(arr[0]) # Accessing the first element
print(arr[5]) # Accessing the sixth element
print(arr[-1]) # Accessing the last element
Slicing Arrays
Slicing allows you to extract subarrays. arr[2:5]
creates a new array containing elements from index 2 up to (but not including) index 5. arr[:4]
retrieves elements from the start up to index 4. arr[5:]
retrieves elements from index 5 to the end. arr[:]
creates a copy of the entire array.
print(arr[2:5]) # Elements from index 2 (inclusive) to 5 (exclusive)
print(arr[:4]) # Elements from the beginning to index 4 (exclusive)
print(arr[5:]) # Elements from index 5 (inclusive) to the end
print(arr[:]) # All elements of the array
Slicing with a Step
A third argument in slicing specifies the step size. arr[::2]
retrieves every other element, starting from the beginning. arr[1::3]
retrieves every third element, starting from index 1.
print(arr[::2]) # Every other element from the beginning
print(arr[1::3]) # Every third element, starting from index 1
Modifying Array Elements with Slicing
Slicing can also be used to modify elements of an array. Here, we assign the value 10 to the elements at indices 2, 3, and 4. It is very important to notice that modification through slicing directly alters the original array.
arr[2:5] = 10 # Assign the value 10 to the elements at indices 2, 3, and 4
print(arr)
Boolean Indexing
Boolean indexing allows you to select elements based on a condition. First, a boolean array (mask) is created based on a condition (arr > 5
). Then, this mask is used to select the elements where the mask is True. The resulting array contains only the elements that satisfy the condition.
arr = np.arange(10)
mask = arr > 5 # Create a boolean mask
print(mask)
print(arr[mask]) # Select elements where the mask is True
Real-Life Use Case
Imagine you have sensor data stored in a NumPy array, and you want to analyze only the data points that exceed a certain threshold. Boolean indexing is perfect for this: you can create a boolean mask indicating data points exceeding the threshold and then use that mask to extract the relevant data for further analysis.
Best Practices
.copy()
if you need an independent copy.
When to use them
Use indexing when you need to access a specific element in the array. Use slicing when you want to extract a contiguous portion of the array. Use boolean indexing when you want to select elements based on a certain condition.
Memory footprint
Basic indexing usually creates a view of the original array, meaning it doesn't duplicate the data in memory. Slicing also creates a view (unless you use .copy()
). Boolean indexing creates a new array containing only the selected elements, increasing memory usage.
Interview Tip
Be prepared to explain the difference between a view and a copy in NumPy. Understand how slicing affects the original array, and when you need to create a copy using the .copy()
method. Be ready to provide an example of how to use boolean indexing to filter data.
FAQ
-
What is the difference between indexing and slicing?
Indexing refers to accessing a single element using its position. Slicing refers to extracting a portion (subarray) of the array. -
Does slicing create a copy or a view of the array?
Slicing usually creates a view of the original array. Changes to the slice will affect the original array. Use the.copy()
method to create a true copy. -
How does boolean indexing work?
Boolean indexing uses a boolean array (mask) of the same shape as the array being indexed to select elements where the corresponding boolean value isTrue
. It creates a new array with only the selected elements.