In this article we will discuss how to drop columns from a DataFrame object.

DataFrame provides a member function drop() i.e.

It accepts a single Label Name or list of Labels and deletes the corresponding columns or rows (based on axis) with that label.
It considers the Labels as column names to be deleted, if axis == 1 or columns == True.

By default it doesn’t modify the existing DataFrame, instead it returns a new dataframe. If we want to delete the rows or columns from DataFrame in place then we need to pass another attribute i.e. inplace=True

Let’s understand by examples,

Create a DataFrame object,

Delete a Single column in DataFrame by Column Name

Contents of DataFrame object dfObj is,

Original DataFrame pointed by dfObj

let’s delete a column ‘Age’ from the above dataframe object,

Contents of the new DataFrame object modDfObj is,

Column Age Deleted from DataFrame

Drop Multiple Columns by Label Names in DataFrame

To drop multiple columns from a DataFrame Object we can pass a list of column names to the drop() function.

For example, drop the columns ‘Age’ & ‘Name’ from the dataframe object dfObj i.e.

Contents of the new DataFrame object modDfObj is,

Columns Age & Name deleted

 

Drop Columns by Index Position in DataFrame

To drop columns by index position, we first need to find out column names from index position and then pass list of column names to drop().

For example delete columns at index position 0 & 1 from dataframe object dfObj i.e.

Contents of the new DataFrame object modDfObj is,

Columns Age & Name deleted

Drop Columns in Place

Delete columns ‘Age’ & ‘Name’ from dataFrame dfObj in Place by passing inplace=True in drop() function i.e.

It will update the contents of dfObj i.e. columns ‘Age’ & ‘Name’ will be deleted from dfObj.

Drop Column If Exists

Before delete a column using drop() always check if column exists or not otherwise drop() will throw a KeyError i.e.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.