w3resource

Pandas DataFrame: Drop a list of rows from a specified DataFrame


36. Drop Rows from DataFrame

Write a Pandas program to drop a list of rows from a specified DataFrame.

Sample data:
Original DataFrame
col1 col2 col3
0 1 4 7
1 4 5 8
2 3 6 9
3 4 7 0
4 5 8 1
New DataFrame after removing 2nd & 4th rows:
col1 col2 col3
0 1 4 7
1 4 5 8
3 4 7 0

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]}
df = pd.DataFrame(d)
print("Original DataFrame")
print(df)
print("New DataFrame after removing 2nd & 4th rows:")
df = df.drop(df.index[[2,4]])
print(df)

Sample Output:

Original DataFrame
   col1  col2  col3
0     1     4     7
1     4     5     8
2     3     6     9
3     4     7     0
4     5     8     1
New DataFrame after removing 2nd & 4th rows:
   col1  col2  col3
0     1     4     7
1     4     5     8
3     4     7     0              

Explanation:

The above code creates a Pandas DataFrame ‘df’ using a Python dictionary ‘d’. The DataFrame has three columns: 'col1', 'col2', and 'col3'.

df = df.drop(df.index[[2,4]]): This code drops rows with indices 2 and 4 using the drop() method with the index parameter set to a list of indices to drop.

Finally print() function prints the resulting DataFrame with the two rows dropped.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to drop rows by a list of index labels and then verify the change by printing the DataFrame shape.
  • Write a Pandas program to remove rows where a specific column has a null value using dropna() with a subset.
  • Write a Pandas program to delete specific rows based on a condition and then reset the index afterward.
  • Write a Pandas program to drop multiple rows by passing a list of indices and then output the remaining rows.

Go to:


Previous: Write a Pandas program to count the NaN values in one or more columns in DataFrame.
Next: Write a Pandas program to reset index in a given DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.