Wednesday, August 27, 2025

๐ŸIndexing, slicing, and filtering of series in Pandas

One of the most powerful features of Pandas Series is the ability to access and manipulate data using indexing, slicing, and filtering. These allow you to retrieve specific elements, subsets, or conditional data easily.

๐Ÿ”น Indexing

A Series can be indexed using either labels (custom names) or integer positions.


import pandas as pd

s = pd.Series([100, 200, 300], index=["a", "b", "c"])

print(s["a"])   # Access by label
print(s[1])     # Access by position
    

๐Ÿ‘‰ Output:


100
200
    

๐Ÿ”น Slicing

You can select multiple values at once using slicing (like Python lists). Slicing works with both positions and labels.


print(s[0:2])     # Position-based slicing
print(s["a":"c"]) # Label-based slicing (inclusive of "c")
    

๐Ÿ‘‰ Output:


a    100
b    200
dtype: int64

a    100
b    200
c    300
dtype: int64
    

๐Ÿ”น Filtering

Filtering allows you to extract data that meets certain conditions.


print(s[s > 150])   # Values greater than 150
print(s[s % 200 == 0]) # Values divisible by 200
    

๐Ÿ‘‰ Output:


b    200
c    300
dtype: int64

b    200
dtype: int64
    

๐Ÿ”น loc and iloc

Pandas provides two powerful indexers:

  • loc → label-based indexing
  • iloc → integer (position-based) indexing

print(s.loc["b"])   # Access by label
print(s.iloc[2])    # Access by integer position
    

๐Ÿ‘‰ Output:


200
300
    

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??