Once a Pandas Series is created, we often need to access its elements. We can do this using index labels, positions, or slicing. Pandas provides flexible ways to work with both numerical and custom indices.
๐น Access by Index Position
You can use the integer position (like in Python lists) to get elements.
import pandas as pd
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])
print(s[0]) # First element
print(s[2]) # Third element
๐ Output:
10
30
๐น Access by Index Label
If a Series has custom labels, you can use them to retrieve elements.
print(s["a"]) # Access using label
print(s["c"]) # Access another element
๐ Output:
10
30
๐น Slicing
You can slice Series just like Python lists, using either positions or labels.
print(s[1:3]) # By position (excludes index 3)
print(s["b":"d"]) # By labels (includes "d")
๐ Output:
b 20
c 30
dtype: int64
b 20
c 30
d 40
dtype: int64
๐น Boolean Indexing
You can filter elements by applying conditions directly on the Series.
print(s[s > 20]) # Select values greater than 20
๐ Output:
c 30
d 40
dtype: int64
No comments:
Post a Comment