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 indexingiloc→ integer (position-based) indexing
print(s.loc["b"]) # Access by label
print(s.iloc[2]) # Access by integer position
๐ Output:
200
300
No comments:
Post a Comment