How To Drop One Or More Columns In Pandas Dataframe
For this exercise, I am using College.csv data.
import pandas as pd
df = pd.read_csv('College.csv')
df.head(1)
Pandas How To Drop One Column By Name
Lets say we want to drop column 'Private' using df.drop()
df.drop('Private',axis=1).head(1)
With above command, we see that 'Private' column has been removed. axis=1 means remove the column. axis=0 means work on row.
With the above command data has not saved. To make the changes, use inplace=True option as shown below.
df.drop('Private',axis=1,inplace=True)
Lets check our dataframe again.
df.head(1)
Pandas How To Drop Multiple Columns By Name
Similarly we can run the same command to drop multiple columns. Lets say we want to drop next two columns 'Apps' and 'Accept'
df.drop(['Apps','Accept'],axis=1).head(1)
To remove multiple columns, we have provided list of columns to df.drop() as shown above. Again for making the change, we need to pass option inplace=True.
df.drop(['Apps','Accept'],axis=1,inplace=True)
Pandas How To Drop One Column By Index Number
We can also remove the column the index number. Let say we want to remove the column 'Enroll' which is index 1. We can get the index using df.columns[index].
df.drop(df.columns[1],axis=1,inplace=True)
df.head(1)
Pandas How To Drop Multiple Columns By Index Number
Lets say we want to drop column Top10perc which is index 1 and F.Undergrad which is index 3. We can do that passing index in a list.
df.drop(df.columns[[1, 3]], axis=1,inplace=True)
df.head(1)
Yes, the columns 'Top10perc' and F.Undergrad have been removed.
Pandas How To Drop Range Of Multiple Columns By Index
Now lets say we want to drop columns 'Top25perc', 'P.Undergrad' and 'Outstate' that are columns from index 1 to 3. We can do that by specifying the index range.
df.drop(df.columns[1:3],axis=1,inplace=True)
df.head(1)
Note, we got only two columns removed, 1:3, 3 is not inclusive. so we have to mention 1:4. Lets do it again. Remove the columns 'Outstate', 'Room.Board' and 'Books' using range 1:4
df.drop(df.columns[1:4],axis=1,inplace=True)
df.head(1)
Wrap Up!
In this post, I have covered the basics of how to drop columns in Pandas dataframe. In the next post, I will cover how to drop rows of Pandas DataFrame.
Related Posts:
Related Notebooks
- 3 Ways to Rename Columns in Pandas DataFrame
- Pandas How To Sort Columns And Rows
- How To Iterate Over Rows In A Dataframe In Pandas
- Join or Merge Lists In Python
- Select Pandas Dataframe Rows And Columns Using iloc loc and ix
- How To Convert Python List To Pandas DataFrame
- How to Export Pandas DataFrame to a CSV File
- How to Sort Pandas DataFrame with Examples
- How To Append Rows With Concat to a Pandas DataFrame