Python Pandas: Deleting Rows and Columns from DataFrame

In Pandas, there is a method drop() which can be used for the purpose of deleting rows and columns. Rows or columns can be easily removed using index labels (rows or column labels), rows or column names. It can also delete multiple rows or columns at once.

When using a multi-index, labels on different levels can be removed by specifying the level. 

Syntax

DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)

Parameters:

  • labels: Index or column label which we want to drop
  • axis: Wether to drop from rows or columns If 0 then rows and if 1 then columns.
  • index or columns: It cannot be used together. It is an alternative to the specified axis.
  • level: It is used to define the level in the case if there are multiple level indexes.
  • inplace: It can make changes in the original DataFrame if it is True.
  • errors: Errors are ignored if any values from the list don't exist and drop the rest of the values.

Return:

DataFrame with dropped values.

Example

import pandas as pd
df=pd.DataFrame({'Name':['Alice','John','Jill','Monica'],
                 'Address':['Jaipur','Delhi','Ajmer','Delhi'],
                 'Age':[22,25,26,23]})
print(df)

Output:

  Name  Address Age

0 Alice  Jaipur  22

1 John   Delhi   25

2 Jill   Ajmer   26

3 Monica Delhi   23
print(df.drop(2))#deleting rows

Output:

  Name   Address Age

0 Alice   Jaipur 22

1 John    Delhi  25

3 Monica  Delhi  23
print(df.drop('Age', axis=1))#deleting columns

Output:

  Name  Address

0 Alice  Jaipur

1 John   Delhi

2 Jill   Ajmer

3 Monica Delhi
Tags