How to remove a group of elements from a pandas series object?


In the pandas series constructor, there is a method called drop() which is used to remove specified rows from the pandas series object. It won’t update the original series object with deleted rows instead of updating the original series object, it will return another series object with the removed rows.

We can use this drop() method on both labeled-based and positional-indexed series objects.

It will raise a Key error if the specified row labels are not found in the index of the series object. We can suppress the errors by setting the errors parameter from raise to ignore. And we have some other parameters labels, axis, level, inplace, and raise.

Example 1

# import pandas package
import pandas as pd

# Creating Series objects
sr = pd.Series([35, 39, 45, 2, 47, 89, 48, 71, 55, 19])
print('Series object:',sr)

# Remove list of elements
result = sr.drop([2,4,6])

# display output
print(result)

Explanation

In the following example, we will delete a set of rows from a series object. initially, we have created a pandas Series with a python list of integer values and the index label are auto-created range index values (location-based index values).

Output

Series object:
0 35
1 39
2 45
3  2
4 47
5 89
6 48
7 71
8 55
9 19
dtype: int64

0 35
1 39
3 2
5 89
7 71
8 55
9 19
dtype: int64

We removed a set of rows from the series object “sr” by specifying the index values of elements by using the python list object. In this example, the rows [2,4,6] are removed.

Example 2

# import pandas package
import pandas as pd

# Creating Series objects
sr = pd.Series([43, 3, 16, 84, 69, 20, 37, 44, 94, 48], index=list("ABCDEFGHIJ"))
print('Series object:',sr)

# Remove list of elements
result = sr.drop(['D', 'E', 'J'])

# display output
print(result)

Explanation

In the following example, we have created a pandas Series with a labeled index. And we removed a row named “C” from the series object by sending the label name to the drop() method.

Output

Series object:
A 43
B  3
C 16
D 84
E 69
F 20
G 37
H 44
I 94
J 48
dtype: int64

A 43
B 3
C 16
F 20
G 37
H 44
I 94
dtype: int64

We have successfully removed the rows “D”, “E”, “J” from the labeled series object “sr”.

Updated on: 09-Mar-2022

779 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements