Wednesday, August 27, 2025

๐ŸAccessing elements in series

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
    

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??