How to drop rows in Pandas

In this post, we will see how to drop rows in Pandas.

You can use DataFrame.drop() method to drop rows in DataFrame in Pandas.

Syntax of DataFrame.drop()

Here,
labels: index or columns to remove.
axis:axis=0 is used to delete rows and axis=1 is used to delete columns. For this post, we will use axis=0 to delete rows. Since axis=0 is the default value, we can ignore this attribute.
columns: It is an alternative to labels and uses to drop columns(Introduced in version 0.21).
index: It is an alternative to labels and uses to drop indices(Introduced in version 0.21).
inplace:If False, it won’t modify the original DataFrame.

Pandas Drop rows based on index

You can specify index labels to drop rows.

Delete single row

Here is an example:

Output:

As you can see, row with index Two got dropped from Pandas DataFrame.

Delete multiple rows

Change highlight line to delete Three and Four indices.

Output:

As you can see, rows with index Three and Four got dropped from Pandas DataFrame.
In case, you want to modify original DataFrame you can pass inplace=True

As you can see, you don’t have to reassign Country_df now.

Pandas Drop rows with conditions

You can also drop rows based on certain conditions.

Here is an example:
Let’s say you want to delete all the rows for which the population is less than or equal to 10000.
You can get index of all such rows by putting conditions and pass it to drop() method.

Output:

Pandas Drop rows with NaN

You can drop values with NaN rows using dropna() method.
Here is an example:

Output:

As you can see, rows that contain NaN were dropped from the Pandas DataFrame.

Pandas Drop duplicate rows

You can drop duplicate rows with DataFrame.drop_duplicates() method.
Here is an example:

Output:

As you can see, rows that contain duplicate data were dropped from the Pandas DataFrame.
That’s all about How to drop rows in Pandas.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *