How to delete a column from Pandas DataFrame

PythonServer Side ProgrammingProgramming

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
raja
Published on 16-Sep-2021 09:31:48
Advertisements