How to delete multiple rows in Pandas DataFrame

In this article, you’ll learn how to delete multiple rows in Pandas DataFrame. The given examples with the solutions will help you to delete multiple rows of Pandas DataFrame.

Example 1: Delete Multiple Rows in Pandas DataFrame using Index Position

# Import the Pandas library as pd
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'col_1': [5, 10, 15, 20],
                   'col_2': [10, 20, 30, 40],
                   'col_3': [30, 60, 90, 50]})

# Display the DataFrame
print(df)

# Delete the Rows at index position 1 and 3
df = df.drop([df.index[1], df.index[3]])

# Display the Modified DataFrame
print(df)

Output:

   col_1  col_2  col_3
0      5     10     30
1     10     20     60
2     15     30     90
3     20     40     50
   col_1  col_2  col_3
0      5     10     30
2     15     30     90

Example 2: Delete Multiple Rows using Index Labels

# Import the Pandas library as pd
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'col_1': [5, 10, 15, 20],
                   'col_2': [10, 20, 30, 40],
                   'col_3': [30, 60, 90, 50]},
                    index=['A', 'B','C','D'])

# Display the DataFrame
print(df)

# Delete the Rows with these index labels
df = df.drop(['B','C'])

# Display the Modified DataFrame
print(df)

Output:

   col_1  col_2  col_3
A      5     10     30
B     10     20     60
C     15     30     90
D     20     40     50
   col_1  col_2  col_3
A      5     10     30
D     20     40     50

Example 3: Delete Rows with Index Range

# Import the Pandas library as pd
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'col_1': [5, 10, 15, 20],
                   'col_2': [10, 20, 30, 40],
                   'col_3': [30, 60, 90, 50]})

# Display the DataFrame
print(df)

# Delete the Rows form index position 1 to 2 
# Note: last element is excluded
df = df.drop(df.index[1:3])

# Display the Modified DataFrame
print(df)

Output:

   col_1  col_2  col_3
0      5     10     30
1     10     20     60
2     15     30     90
3     20     40     50
   col_1  col_2  col_3
0      5     10     30
3     20     40     50

If you want to learn Pandas, I recommend this book and free resource.

Leave a Comment

Your email address will not be published.