Drop or delete column in python pandas

In this tutorial we will learn how to  drop or delete column in python pandas by index,  drop column in pandas by name and drop column in python pandas by position. Lets see example of each.

Create Dataframe

import pandas as pd
import numpy as np

#Create a DataFrame
d = {
    'Name':['Alisa','Bobby','jodha','jack','raghu','Cathrine',
            'Alisa','Bobby','kumar','Alisa','Alex','Cathrine'],
    'Age':[26,24,23,22,23,24,26,24,22,23,24,24],
     
       'Score':[85,63,55,74,31,77,85,63,42,62,89,77]}

df = pd.DataFrame(d,columns=['Name','Age','Score'])
df

The resultant dataframe will be

Drop or delete columns in python pandas 1

 

Drop a column by name:

Lets see an example of how to drop a column by name in python pandas


# drop a column based on name

df.drop('Age',axis=1)

The above code drops the column named ‘Age’, the argument axis=1 denotes column, so the resultant dataframe will be

Drop or delete columns in python pandas 2

 

Drop a column based on column index:

Let’s see an example on dropping the column by its index in python pandas


# drop a column based on column index

df.drop(df.columns[2],axis=1)

In the above example column with index 2 is dropped(3rd column). So the resultant dataframe will be

Drop or delete columns in python pandas 3

 

Delete a column based on column name:


# delete a column

del df['Age']
df

In the above example column with the name ‘Age’ is deleted. So the resultant dataframe will be

Drop or delete columns in python pandas 4

 

previous-small Drop or delete columns in python pandas                                                                                                                next_small Drop or delete columns in python pandas