![]() |
VOOZH | about |
In this, we will cover basic slicing and advanced indexing in the NumPy. NumPy arrays are optimized for indexing and slicing operations making them a better choice for data analysis projects.
Indexing is used to extract individual elements from a one-dimensional array. It can also be used to extract rows, columns or planes in a multi-dimensional NumPy array.
The table below shows positive and negative indexing positive indexing starts from 0 (left to right), while negative indexing starts from -1 (right to left).
Negative Index | -5 | -4 | -3 | -2 | -1 |
|---|---|---|---|---|---|
| Element | 23 | 21 | 55 | 65 | 23 |
| Positive Index | 0 | 1 | 2 | 3 | 4 |
Indexing with index arrays lets you fetch multiple elements from a NumPy array at once using their index positions. Unlike slicing, it returns a new copy of the data.
Example: Here, we create an array in decreasing order and use another array of indices to extract specific elements.
('Array:', array([10, 8, 6, 4, 2]))
('Elements at specified indices:', array([4, 8, 6]))
Explanation: arr[[3, 1, 2]] creates a new array by picking elements from indices 3, 1 and 2 of the original array, resulting in [4, 8, 6].
Basic slicing and indexing are used to access specific elements or a range of elements from a NumPy array. It returns a view of the original array (not a copy). The general syntax is x[start:stop:step], where:
Example: Here, we use different slicing patterns to access array elements.
('a[15] =', 15)
('a[-8:17:1] =', array([12, 13, 14, 15, 16]))
('a[10:] =', array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
Using Ellipsis (…): Ellipsis (...) is used to represent all dimensions in a multi-dimensional array, making it easier to access deep elements.
Example: Here, we use ellipsis to access the second element across all inner lists.
[[ 2 5] [ 8 11]]
Explanation: b[..., 1] accesses the second element (index 1) from each inner list across all dimensions.
Advanced indexing in NumPy allows you to extract complex data patterns using arrays of integers or Booleans. Unlike basic slicing, it returns a copy of the data, not a view. Advanced indexing occurs when the index object is:
There are two types of Advanced Indexing in NumPy array indexing:
Integer Array Indexing: This method selects elements using integer arrays. Each pair of indices from different dimensions identifies a specific element.
Example: Here, we extract elements using integer-based positions.
[1 3 6]
Explanation: Here, positions (0,0), (1,0) and (2,1) are selected from the array, returning elements 1, 3 and 6.
Boolean Indexing: This indexing has some boolean expressions as the index. Those elements are returned which satisfy that Boolean expression. It is used for filtering the desired element values.
Example 1: Here, we select numbers greater than 50.
[ 80 100]
Example 2: Here, we select rows whose sum is a multiple of 10.
[[ 5 5] [16 4]]