Skip to content
Home » pandas Part 7 – Slicing and Indexing Series Objects

pandas Part 7 – Slicing and Indexing Series Objects

Spread the love

slicing series objects

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:

In [1]:
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':]
Out[1]:
C    0.87
D    2.76
E    3.12
F    5.79
dtype: float64

And now let’s make another slice, from the element with the index ‘B’ to the element with the index ‘E’:

In [2]:
nums['B':'E']
Out[2]:
B    4.11
C    0.87
D    2.76
E    3.12
dtype: float64

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:

In [3]:
nums[1:4]
Out[3]:
B    4.11
C    0.87
D    2.76
dtype: float64

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:

In [4]:
# regular indexing
nums['D']
Out[4]:
2.76
In [6]:
# masking
nums[(nums > 2.5) & (nums < 4.5)]
Out[6]:
B    4.11
D    2.76
E    3.12
dtype: float64
In [7]:
# fancy indexing
nums[['F', 'A', 'B']]
Out[7]:
F    5.79
A    2.35
B    4.11
dtype: float64

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love
Tags:

Leave a Reply