Python | Pandas Index.drop ()

Python Methods and Functions

Index.drop() Pandas Index.drop() new index with the list of missing tags removed. This function is similar to Index.delete () except that in this function we pass in the label names, not 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 () to remove passed labels from the index.

# import pandas as pd

import pandas as pd

 
# Create index

idx = pd.Index ( [ 'Jan' , ' Feb' , 'Mar' , ' Apr' , 'May' , ' Jun'

'Jul' , 'Aug' , ' Sep' , ' Oct' , 'Nov' , 'Dec' ])

 
# Print index
idx

Output:

Let's drop the month January and December from the index.

# Passing a list containing tags
# to be excluded from the index

idx.drop ([ 'Jan' , 'Dec' ])

Output:

As we can see from the output, the function returned an object that does not contain the labels that we passed to Index.drop () .

Example # 2: Use Index.drop () to remove the list of placemarks in the index containing date and time data.

# import pandas as pd

import pandas as pd

 
# Create first index

id x = pd.Index ([ '2015-10-31' , '2015-12-02' , '2016-01-03' ,

  '2016-02-08' , ' 2017-05-05' , '2014-02-11' ])

 
# Print index
idx

Output:

Now let's strip some dates from the index.

# Pass values ​​to remove from the index

idx.drop ([ '2015-12-02' , ' 2016-02-08' ])

Output:

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





Get Solution for free from DataCamp guru