How to delete a column from Pandas DataFrame



To delete a column from a DataFrame, use del(). You can also use pop() method to delete. Just drop it using square brackets. Mention the column to be deleted in the brackets and that’s it, for example βˆ’

del dataFrame[β€˜ColumnName’]

Import the required library with an alias βˆ’

import pandas as pd

Create a Pandas DataFrame βˆ’

dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

Now, delete a column β€œCar” from a DataFrame βˆ’

del dataFrame['Car']

Example

Following is the code βˆ’

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame ...\n",dataFrame

# deleting a column
del dataFrame['Car']

print"\nDataFrame after deleting a column = \n",dataFrame

Output

This will produce the following output βˆ’

DataFrame ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3  Mustang     80
4  Bentley    110
5   Jaguar     90

DataFrame after deleting a column =
   Units
0   100
1   150
2   110
3    80
4   110
5    90
Updated on: 2021-09-16T09:31:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements