Python | Pandas Index.drop()

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output :

Let’s drop the month of ‘Jan’ and ‘Dec’ from the Index.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output :

Now, let’s drop some dates from the Index.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

As we can see in the output, the Index.drop() function has dropped the passed values from the Index.



My Personal Notes arrow_drop_up

Recommended Posts:



    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.