This article will tell you how to remove elements from a pandas Series object and how to empty the pandas Series object.
1. How To Remove Pandas Series Element Example.
- We should call the pandas Series object’s drop method to remove the elements specified by the provided index label list.
>>> import pandas as pd >>> >>> dict_data = {'Jerry' : 100, 'Tom' : 90, 'Jack' : 80} >>> >>> ser_obj = pd.Series(dict_data) >>> >>> print(ser_obj) Jerry 100 Tom 90 Jack 80 dtype: int64 >>> >>> ser_obj.drop('Jack', inplace=False) # drop element that index label is Jack, set inplace to False means it will not change the Series object ser_obj. Jerry 100 Tom 90 dtype: int64 >>> >>> print(ser_obj) Jerry 100 Tom 90 Jack 80 dtype: int64 >>> >>> ser_obj.drop('Jack', inplace=True) # set inplace to True means it will remove the element in the Series object ser_obj. >>> >>> print(ser_obj) Jerry 100 Tom 90 dtype: int64
2. How To Empty Pandas Series Object.
- In the below source code, we will iterate all the Series object’s index labels and then drop each element by the index label to achieve the goal of emptying the Series object.
>>> idx = ser_obj.index # get the Series object's index labels. >>> >>> idx_arr = idx.array # get the label in an array. >>> # loop the label array, and drop each Series object element by the label. >>> for key in idx_arr: ... print(key) ... ser_obj.drop(key, inplace=True) ... Jerry Tom Jack >>> print(ser_obj) # now the Series object is empty. Series([], dtype: int64)