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 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 axis
Example #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 |
Output :
Let’s drop the month of ‘Jan’ and ‘Dec’ from the Index.
# Passing a list containing the labels # to be dropped from the Index idx.drop([ 'Jan' , 'Dec' ]) |
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 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 |
Output :
Now, let’s drop some dates from the Index.
# Passing the values to be dropped from the Index idx.drop([ '2015-12-02' , '2016-02-08' ]) |
Output :
As we can see in the output, the Index.drop()
function has dropped the passed values from the Index.