Pandas

2.Pandas Series: Indexing and Slicing

What is Indexing and Slicing in Pandas Series?

Indexing allows us to access specific elements of a Pandas Series, while Slicing helps us retrieve a subset of the Series based on index positions or labels.

Pandas provides two ways to access elements in a Series:

  1. Indexing – Accessing individual elements using their index.
  2. Slicing – Retrieving a range of elements using Python’s slicing syntax.

1. Indexing in Pandas Series

You can access elements of a Pandas Series using:
Default numeric index (0,1,2,…)
Custom index (if defined)

Example 1: Indexing using Default Numeric Index

import pandas as pd  

# Creating a Series  
data = pd.Series([10, 20, 30, 40, 50])  

# Accessing elements using numeric index  
print(data[0])  # First element  
print(data[3])  # Fourth element  

Output:

10  
40  

🔹 Here, data[0] gives the first element and data[3] gives the fourth element.

Example 2: Indexing using Custom Labels

import pandas as pd  

# Creating a Series with custom index  
data = pd.Series([100, 200, 300], index=['A', 'B', 'C'])  

# Accessing elements using custom labels  
print(data['A'])  # First element  
print(data['C'])  # Third element  

Output:

100  
300  

🔹 When a custom index is used, we can access elements using data[‘label’] instead of numeric positions.


2. Slicing in Pandas Series

Slicing allows retrieving multiple elements from a Series.

Example 3: Slicing using Numeric Index

import pandas as pd  

# Creating a Series  
data = pd.Series([10, 20, 30, 40, 50, 60])  

# Slicing a range of elements  
print(data[1:4])  # Elements from index 1 to 3 (4 is excluded)

Output:

1    20  
2    30  
3    40  
dtype: int64  

🔹 The slicing syntax [start:end] selects elements from start index to end-1.

Example 4: Slicing using Custom Index

import pandas as pd  

# Creating a Series with custom index  
data = pd.Series([100, 200, 300, 400, 500], index=['A', 'B', 'C', 'D', 'E'])  

# Slicing using labels  
print(data['B':'D'])  # Elements from index 'B' to 'D'

Output:

B    200  
C    300  
D    400  
dtype: int64  

🔹 Unlike numeric slicing, custom index slicing is inclusive, meaning ‘D’ is included.


Key Takeaways:

Indexing is used to access individual elements, while slicing retrieves multiple elements.
✅ Pandas supports both numeric and custom index-based access.
✅ Numeric slicing excludes the last index (end-1), whereas custom index slicing includes the last label.

Leave a Reply

Your email address will not be published. Required fields are marked *