Python | Pandas Index.drop()
Last Updated :
16 Dec, 2018
Improve
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas
Python3
Output :
Let's drop the month of 'Jan' and 'Dec' from the Index.
Python3 1==
Output :
As we can see in the output, the function has returned an object which does not contain the labels that we passed to the
Python3
Output :
Now, let's drop some dates from the Index.
Python3 1==
Output :
As we can see in the output, the
Index.drop()
function make new Index with passed list of labels deleted. The function is similar to the Index.delete()
except in this function we pass the label names rather than the position values.
Syntax: Index.drop(labels, errors='raise') Parameters : labels : array-like errors : {‘ignore’, ‘raise’}, default ‘raise’ If ‘ignore’, suppress error and existing labels are dropped. Returns : dropped : Index Raises : KeyError. If not all of the labels are found in the selected axisExample #1: Use
Index.drop()
function to drop the passed labels from the Index.
# importing pandas as pd
import pandas as pd
# Creating the Index
idx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
# Print the Index
idx

# Passing a list containing the labels
# to be dropped from the Index
idx.drop(['Jan', 'Dec'])

Index.drop()
function.
Example #2: Use Index.drop()
function to drop a list of labels in the Index containing datetime data.
# importing pandas as pd
import pandas as pd
# Creating the first Index
idx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03',
'2016-02-08', '2017-05-05', '2014-02-11'])
# Print the Index
idx

# Passing the values to be dropped from the Index
idx.drop(['2015-12-02', '2016-02-08'])

Index.drop()
function has dropped the passed values from the Index.