Pandas Series slicing is a process of selecting a group of elements from a Series object. A Series in Pandas is a one-dimensional labeled array that works similarly to the one-dimensional ndarray (NumPy array) but with labels, which are also called indexes.
Pandas Series slicing is very similar to Python and NumPy slicing but it comes with additional features, like slicing based on both position and labels. In this tutorial by Vista Academy, we will learn about the slicing operations on Pandas Series objects.
Series slicing can be done by using the [:] operator, which allows you to select subsets of elements from the series object using specified start and end points.
Syntax:
Series[start:stop:step]: Selects elements from start to end with specified step value.Series[start:stop]: Selects items from start to stop with step 1.Series[start:]: Selects items from start to the rest of the object with step 1.Series[:stop]: Selects the items from the beginning to stop with step 1.Series[:]: Selects all elements from the series object.Example: Slicing range of values from a Series
import pandas as pd
import numpy as np
data = np.array(['a', 'b', 'c', 'd'])
s = pd.Series(data)
# Display the Original series
print('Original Series:', s, sep='\n')
# Slice the range of values
result = s[1:3]
# Display the output
print('Values after slicing the Series:', result, sep='\n')
Output:
Original Series:
0 a
1 b
2 c
3 d
dtype: object
Values after slicing the Series:
1 b
2 c
dtype: object
Example: Slicing the First Three Elements
import pandas as pd
s = pd.Series([1,2,3,4,5], index=['a','b','c','d','e'])
# Retrieve the first three elements
print(s[:3])
Output:
a 1
b 2
c 3
dtype: int64
Example: Slicing the Last Three Elements
import pandas as pd
s = pd.Series([1,2,3,4,5], index=['a','b','c','d','e'])
# Retrieve the last three elements
print(s[-3:])
Output:
c 3
d 4
e 5
dtype: int64
A Pandas Series is like a fixed-size Python dict in that you can get and set values by index labels.
Example: Slicing group of elements using labels
import pandas as pd
s = pd.Series([1,2,3,4,5], index=['a','b','c','d','e'])
# Slice multiple elements
print(s['a':'d'])
Output:
a 1
b 2
c 3
d 4
dtype: int64
Example: Slicing first three elements using labels
import pandas as pd
s = pd.Series([1,2,3,4,5], index=['a','b','c','d','e'])
# Slice using labels
print(s[:'c'])
Output:
a 1
b 2
c 3
dtype: int64
After slicing a Series, you can also modify the values by assigning new values to the sliced elements.
Example: Modify values of first two elements
import pandas as pd
s = pd.Series([1,2,3,4,5])
# Display the original series
print("Original Series:\n", s)
# Modify the values
s[:2] = [100, 200]
print("Series after modifying the first two elements:", s)
Output:
Original Series:
0 1
1 2
2 3
3 4
4 5
dtype: int64
Series after modifying the first two elements:
0 100
1 200
2 3
3 4
4 5
dtype: int64
