Indexing, Slicing, and Boolean Masking in NumPy
Hey guys! Welcome back to our NumPy for Data Science series. This is going to be the third article of this series. In our previous articles, we discussed the introduction of NumPy, and How to Create and Manipulate NumPy Arrays. We also saw some code examples to understand the concepts better. So, if you haven’t read the previous articles yet, check them out from our NumPy Series.
Alright! Let’s start our today’s topic and see how things work in detail. As we know already, in the field of Data Science, working with large datasets is a common task. NumPy makes this process easier by providing efficient ways to access and manipulate data using indexing, slicing, and boolean masking. We can use these techniques for selecting specific elements, rows, or columns from an array based on conditions.
Indexing in NumPy
Indexing allows us to access individual elements in an array using their positions.
Indexing in 1D Arrays
In a one-dimensional NumPy array, elements are accessed using zero-based indexing.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # Output: 10
print(arr[2]) # Output: 30
print(arr[-1]) # Output: 50Negative indexing accesses from the end of the array. That’s why we got 50 as the output, which is present at the end of the array.
Indexing in 2D Arrays
Let’s first create a two-dimensional array.
arr2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])For 2D arrays, we need to use row and column indices.
print(arr2d[1, 2]) # Output: 6
print(arr2d[2, 0]) # Output: 7In the first case, I used Row index 1 and Column index 2, which gave us 6 as a result. In the second case, I wanted to fetch the first element in the 3rd row, which is 7. So, I simply used [2, 0]. Don’t get confused in the numbers. I told earlier that elements are accessed using zero-based indexing in NumPy. So, for the 3rd row, we have to use index 2.
I think it’s clear now.
- The first index represents the row.
- The second index represents the column.
It’s that simple, right?
Slicing in NumPy
We extract a subset of elements from an array using Slicing.
Slicing in 1D Arrays
The basic slicing syntax is: array[start:stop:step]
- start → Starting index (included)
- stop → Ending index (excluded)
- step → Step size (optional)
If we won’t provide the starting index, it’ll start from 0 by default. And if we won’t provide the ending index, it’ll go to the end of the array. Step size is an optional thing, depends on whether we need it or not.
arr = np.array([10, 20, 30, 40, 50, 60])
print(arr[1:4]) # Output: [20 30 40]
print(arr[:3]) # Output: [10 20 30]
print(arr[2:]) # Output: [30 40 50 60]
print(arr[::2]) # Output: [10 30 50]- First operation indexes from 1 to 3, where 1 is included and 3 is excluded. That’s why the output is [20, 30, 40]. 50 is at index 3, which is not included, as expected.
- Second operation started from beginning, as I told earlier, when there is no start index provided, it’ll start from index 0 by default.
- Similarly, the third operation started from index 2, and went to the end of the array, as we didn’t provide any end index.
- The last operation only fetch all elements from beginning to the end with a step size of 2. As we neither provided the start index nor the end index. So, it considered the entire array, but then we also gave a step size. So, it’ll give the alternate elements from the array. We got 10, then 20 is skipped, got 30, 40 is skipped, got 50 and 60 is skipped. Well, if we wanted to start from 20, we just had to start it from index 1.😉
Slicing in 2D Arrays
For multi-dimensional arrays, we need to specify slices for rows and columns separately.
arr2d = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
arr2d[0:2, 1:3]
# Output:
array([[2, 3],
[6, 7]]
Okay! So, first, 0:2 selects rows 0 and 1 and then 1:3 selects columns 1 and 2. We know end index is excluded. So, this is how it works. 0:2 takes first and second rows and excludes the 3rd row, which is at index 2. Now, 1:3 takes the second column and third column, excluding the fourth column, which is at index 3. Let’s take one more example.
arr2d[:, 2] # Output: array([ 3, 7, 11])As we haven’t provided the start and end values for the rows, it’ll select all three rows. Next, for column, we only provided index 2, which means it’ll take the third column.
arr2d[1, :] # Output: array([5, 6, 7, 8])It’s the same case as above. We’ve just done the same with column this time. So, it selects the second row which is at index 1, and all three the columns.
Boolean Masking in NumPy
We use Boolean masking when we want to filter data based on some conditions. Okay, let’s understand this with some examples.
Boolean Masking in 1D Arrays
arr = np.array([10, 20, 30, 40, 50])
mask = arr > 25
mask # Output: array([False, False, True, True, True])Here, the mark will create a Boolean Array. It’ll select elements which satisfies the condition, which are greater than 25, based on that it’ll return either True or False.
filtered_arr = arr[mask]
filtered_arr # Ouput: array([30, 40, 50])When I applied this mask arr[mask], it selected elements where the condition is True, which gave us 30, 40, and 50 which are all greater than 25. As 10 and 20 are less than 25, it’ll not select those elements.
Boolean Masking in 2D Arrays
arr2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
mask = arr2d > 4
mask
# Output:
array([[False, False, False],
[False, True, True],
[ True, True, True]])So, mask will return True for the numbers greater than 4, and False otherwise.
arr2d[mask] # Output: array([5, 6, 7, 8, 9])So, this is how we can filter elements based on the condition.
Get NIBEDITA (NS)’s stories in your inbox
Join Medium for free to get updates from this writer.
Alright, let’s combine Multiple Conditions this time. We can use Logical Operators, like & (AND), | (OR), and ~ (NOT).
arr = np.array([10, 20, 30, 40, 50])
mask = (arr > 10) & (arr < 40)
arr[mask] # Output: array([20, 30])So, our mask will select numbers between 10 and 40. And the arr[mask] will return the numbers that lie b/w 10 and 40. As 10 and 40 are exclusive, it didn’t returned them. But if we want them to be included in the filtered data, we can use ≤ and ≥ operators. Well, in python, we have to use as <= and >=, not like we do in Matematics. But the logic is the same.
Alright! So, to summarize stuffs, today we covered:
- Indexing lets us access individual elements using row & column indices.
- Slicing helps extract a portion of an array using [start:stop:step].
- Boolean Masking filters elements based on conditions.
These techniques are powerful tools for working with numerical datasets in Data Science & Analytics!
And that’s all for today!
Check out related Lists:
Thanks for reading! 😊
A message from our Founder
Hey, Sunil here. I wanted to take a moment to thank you for reading until the end and for being a part of this community.
Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community. ❤️
If you want to show some love, please take a moment to follow me on LinkedIn, TikTok, Instagram. You can also subscribe to our weekly newsletter.
And before you go, don’t forget to clap and follow the writer️!








