Python Pandas - Make new Index with passed list of labels deleted

PythonPandasServer Side ProgrammingProgramming

To make new Index with passed list of labels deleted, use the index.drop() method. Pass the list of labels in it.

At first, import the required libraries −

import pandas as pd

Creating the index −

index = pd.Index(['Car','Bike','Truck','Ship','Airplane'])

Display the index −

print("Pandas Index...\n",index)

A list containing labels to be dropped are passed −

print("\nUpdated index after deleting labels...\n",index.drop(['Bike', 'Ship']))

Example

Following is the code −

import pandas as pd

# Creating the index
index = pd.Index(['Car','Bike','Truck','Ship','Airplane'])

# Display the index
print("Pandas Index...\n",index)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Return a tuple of the shape of the underlying data
print("\nA tuple of the shape of underlying data...\n",index.shape)

# a list containing labels to be dropped are passed
print("\nUpdated index after deleting labels...\n",index.drop(['Bike', 'Ship']))

Output

This will produce the following code −

Pandas Index...
Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')

The dtype object...
object

A tuple of the shape of underlying data...
(5,)

Updated index after deleting labels...
Index(['Car', 'Truck', 'Airplane'], dtype='object')
raja
Published on 13-Oct-2021 11:31:13

Advertisements