When we were talking about Series objects we saw that slicing Series objects may be pretty straightforward. Let’s have a look at the same example that we used before:
import numpy as np
import pandas as pd
nums = pd.Series([2.35, 4.11, 0.87, 2.76, 3.12, 5.79],
index = ['A', 'B', 'C', 'D', 'E', 'F'])
# slice from element at index 'C' to the end
nums['C':]
And now let’s make another slice, from the element with the index ‘B’ to the element with the index ‘E’:
nums['B':'E']
You probably noticed that the second index in the square brackets is not exclusive, as you might have expected. This is how slicing works if we use the explicit label indices like above. But we can always use the implicit positional integer index (the one that a regular Python list uses for example) as well. In our case the positional index that corresponds to the label index ‘B’ is 1 (positional indices are 0-based) and the one that corresponds to ‘E’ is 4, so:
nums[1:4]
This time the second index is exclusive. So, you must be careful about which index you use: the label based one or the positional integer one. This may be problematic if the label indices are integers as well, but we’re going to have a look at such a case in the next part of this series.
Now, let’s quickly see at how we can index Series objects. Well, actually we can use the same indexing methods as with numpy arrays, which include the regular straightforward indexing, masking and fancy indexing. If you want to learn more about masking and fancy indexing, you can read my articles in the numpy series.
Let’s have a look:
# regular indexing
nums['D']
# masking
nums[(nums > 2.5) & (nums < 4.5)]
# fancy indexing
nums[['F', 'A', 'B']]
Here’s the video version of the article: