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??