Pandas Series: drop() function
Remove series with specified index labels
The drop() function is used to get series with specified index labels removed.
Remove elements of a Series based on specifying the index labels. When using a multi-index, labels on different levels can be removed by specifying the level.
Syntax:
Series.drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
labels | Index labels to drop. | single label or list-like | Required |
axis | Redundant for application on Series. | 0 Default Value: 0 |
Required |
index, columns | Redundant for application on Series, but index can be used instead of labels. | Default Value: None | Required |
level | For MultiIndex, level for which the labels will be removed. | int or level name | optional |
inplace | If True, do operation inplace and return None. | bool Default Value: False |
Required |
errors | If ‘ignore’, suppress error and only existing labels are dropped. | {‘ignore’, ‘raise’} Default Value: ‘raise’ |
Required |
Returns: Series
Series with specified index labels removed.
Raises: KeyError
If none of the labels are found in the index.
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(data=np.arange(3), index=['P', 'Q', 'R'])
s
Output:
P 0 Q 1 R 2 dtype: int32
Example - Drop labels Q en R:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(data=np.arange(3), index=['P', 'Q', 'R'])
s.drop(labels=['Q', 'R'])
Output:
P 0 dtype: int32
Example - Drop 2nd level label in MultiIndex Series:
Python-Pandas Code:
import numpy as np
import pandas as pd
midx = pd.MultiIndex(levels=[['dog', 'cow', 'cat'],
['speed', 'weight', 'length']],
codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 2, 0, 1, 2, 0, 1, 2]])
s = pd.Series([50, 30, 1.6, 30, 250, 1.5, 40, 18, 1.1],
index=midx)
s
Output:
dog speed 50.0 weight 30.0 length 1.6 cow speed 30.0 weight 250.0 length 1.5 cat speed 40.0 weight 18.0 length 1.1 dtype: float64
Python-Pandas Code:
import numpy as np
import pandas as pd
midx = pd.MultiIndex(levels=[['dog', 'cow', 'cat'],
['speed', 'weight', 'length']],
codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 2, 0, 1, 2, 0, 1, 2]])
s = pd.Series([50, 30, 1.6, 30, 250, 1.5, 40, 18, 1.1],
index=midx)
s.drop(labels='weight', level=1)
Output:
dog speed 50.0 length 1.6 cow speed 30.0 length 1.5 cat speed 40.0 length 1.1 dtype: float64
Previous: Series containing counts of unique values in Pandas
Next: Series-droplevel() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/pandas/series/series-drop.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics