हिंदी

Explain how we can access elements of a series using slicing. Give an example to support your answer. - Informatics Practices

Advertisements
Advertisements

प्रश्न

Explain how we can access elements of a series using slicing. Give an example to support your answer.

कोड लेखन
स्पष्ट कीजिए
Advertisements

उत्तर

Slicing in a Pandas Series allows us to retrieve a portion of the data by defining a range of indices. It functions in a similar way to slicing in Python lists or NumPy arrays.

Syntax: 

Series[start: stop: step].
  • start → starting index (inclusive)
  • stop → ending index (exclusive)
  • step → interval between elements (optional, default is 1)

Example:

import pandas as pd
# Creating a Series
ser = pd.Series([10, 20, 30, 40, 50], index=["A", "B", "C", "D", "E"])
# Accessing elements using slicing
print ("Slice from index B to D:\n", ser["B":"D"]) # Label-based slicing
print ("\nSlice using positional indices:\n", ser[1:4]) # Positional slicing
print ("\nEvery second element:\n", ser[::2]) # Step slicing

Output:

Slice from index B to D:
                     B   20
                     C   30
                     D   40
           dtype: int64

Slice using positional indices:
                     B   20
                     C   30
                     D   40
           dtype: int64

Every second element:
                     A   10
                     C   30
                     E   50
           dtype: int64

shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
2024-2025 (March) Set 4

APPEARS IN

Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×