Home »
Python »
Python Programs
How to drop a list of rows from Pandas DataFrame?
Given a DataFrame, we have to drop a list of rows from it.
Submitted by Pranit Sharma, on May 11, 2022
Rows in pandas are the different cell (column) values which are aligned horizontally and also provides uniformity. Each row can have same or different value. Rows are generally marked with the index number but in pandas we can also assign index name according to the needs. In pandas, we can create, read, update and delete a column or row value. Here, we are going to learn, how to drop a list of rows from DataFrame? For this purpose, we will use pandas.DataFrame.drop() method.
pandas.DataFrame.drop() Method
This method is used to remove a specified row or column from the pandas DataFrame. Since rows and columns are based on index and axis values respectively, by passing index or axis value inside DataFrame.drop() method we can delete that particular row or column. Below is the syntax:
Syntax:
DataFrame.drop(
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors='raise'
)
# or
df.drop(axis=None) # deletes a specified column.
df.drop(index=None) # deletes a specified row.
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example:
# Importing pandas package
import pandas as pd
# Creating a Dictionary
dict = {
'Name':['Amit','Bhairav','Chirag','Divyansh','Esha'],
'DOB':['07/12/2001','08/11/2002','09/10/2003','10/09/2004','11/08/2005'],
'Gender':['Male','Male','Male','Male','Female'],
'Salary':[25000,35000,42000,17000,27000]
}
# Creating a DataFrame, since we need to drop a list of row
# and we know that rows have particular indexes
# so we will assign some names to each row for
# better understanding
df = pd.DataFrame(dict, index=['A','B','C','D','E'])
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
Output:
Now, we will drop a list of rows where index = 'B' and 'C'.
# Dropping rows with index B and C
result = df.drop(['B','C'])
# Display Result
print("Modified DataFrame\n",result)
Output:
Python Pandas Programs »
ADVERTISEMENT
ADVERTISEMENT