Overview:
- From a pandas Series a set of elements can be removed using the index, index labels through the methods drop() and truncate().
- The drop() method removes a set of elements at specific index locations. The locations are specified by index or index labels.
- The truncate() method truncates the series at two locations: at the before-1 location and after+1 location. It returns the resultant new series.
- In the similar way, if the data is from a 2-dimensional container like pandas DataFrame, the drop() and truncate() methods of the DataFrame class can be used.
Example – Remove elements at specific index locations using drop():
# 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:
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():
# 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); |
Output:
Original Series: 0 10 1 20 2 30 3 40 4 50 5 60 6 70 7 80 8 90 9 100 dtype: int64 New series obtained after truncation: 4 50 5 60 6 70 7 80 8 90 dtype: int64 |