Unlocking the Power of Indexing & Slicing in Pandas Series

Data Science Delight
3 min readJul 28, 2023

--

Welcome! to the ultimate guide on “Unlocking the Power of Indexing & Slicing in Pandas Series”. In this session, we will learn how to access and manipulate data using indexing & slicing techniques.

Photo by Iewek Gnos on Unsplash

Before diving into the topic! I would like to request the readers to visit my previous article, as it covers the fundamental concepts that will serve as a solid foundation for the content discussed in this tutorial. You can visit the previous article here.

Additionally, please “Follow” me on Medium as it would encourage me to write more useful content on Data Science and Machine Learning:

Now, Let’s dive into the topic!

Indexing in Pandas Series

Indexing is used to select a specific row or column from a DataFrame. You can use various indexing techniques such as loc, iloc to select rows or columns. We use square bracket notation to perform indexing.

Using Integer Indexing:

import pandas as pd

# Create a Pandas Series
data = pd.Series([10, 20, 38, 40, 50])

# Access the element at index position 2
print(data[2]) # Output: 38

Using Custom Index Label:

import pandas as pd

# Create a Pandas Series with custom index labels
data = pd.Series([10, 20, 28, 40, 50], index=['A', 'B', 'C', 'D', 'E'])

# Access the element with index label 'C'
print(data['C']) # Output: 28
Photo by Amr Taha™ on Unsplash

Slicing

Slicing is used to select a subset of rows or columns from a Series or a DataFrame.

Slicing with Integer Positions:

import pandas as pd

# Create a Pandas Series
data = pd.Series([10, 20, 32, 40, 50])

# Slice elements from index position 1 to 3 (exclusive)
print(data[1:3]) # Output: 20, 32

Slicing with Custom Index Lables:

import pandas as pd

# Create a Pandas Series with custom index labels
data = pd.Series([10, 20, 30, 45, 50], index=['A', 'B', 'C', 'D', 'E'])

# Slice elements from index label 'B' to 'D' (inclusive)
print(data['B':'E']) # Output: 20, 30, 45

Slicing with Step Size:

import pandas as pd

# Create a Pandas Series
data = pd.Series([11, 22, 33, 44, 55])

# Slice elements with a step size of 2
print(data[::2]) # Output: 11, 33, 55

NOTE:

Indexing & Slicing in Pandas Series are zero-based, meaning the first element has index 0, the second has index 1, and so on. Understanding these concepts are important while working with data analysis or data manipulation.

If you like it, please consider giving it a clap and please “Follow” me on Medium for more such insightful contents on Data Science and ML.

Your support means the world to me! Thank You.

--

--

Data Science Delight

Content Creator | Sharing insights & tips on data science | Instagram: @datasciencedelight | YouTube: https://www.youtube.com/channel/UCpz2054mp5xfcBKUIctnhlw