Remove elements from a pandas Series using drop() and truncate() methods
Elements from a pandas Series can be removed and new a Series object can be created through the methods drop() and truncate() by specifying the index and index labels of the series.
Example – Remove elements at specific index locations using drop()
python
# Python example program to remove a set of elements
# specified by a set of indexes
import pandas as pds
alphabets = ["a","b","c","d","e","f","g","h","i","j"];
series = pds.Series(alphabets);
# List of indices at which the elements need to be removed
newSeries = series.drop([0, 2, 4, 6, 8]);
print("Original Series:");
print(series);
print("New Series returned after removing elements at every alternate index:");
print(newSeries);
Output
Output
Original Series:
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
dtype: object
New Series returned after removing elements at every alternate index:
1 b
3 d
5 f
7 h
9 j
dtype: object
Example - Remove elements at specific index locations using truncate()
python
# Example Python program to truncate a pandas Series
# at specific index locations
import pandas as pds
# Create a pandas Series
series = pds.Series([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]);
print("Original Series:");
print(series);
# Truncate the Series to get a new Series
newSeries = series.truncate(4, 8, copy = False);
print("New series obtained after truncation:");
print(newSeries);
We'd like to use Google Analytics cookies to count visits and see which tutorials are useful.
They are only set if you accept. We don't use advertising cookies and we don't sell your data.
You can change your choice any time from “Your privacy choices” at the bottom of every page.
Privacy Policy
Your privacy choices
Your browser sent a Global Privacy Control signal, so analytics is off unless you turn it on here.
Strictly necessary
Remembers this choice in your browser. No cookies, nothing sent to anyone.Always on