Pandas DataFrame: Drop a list of rows from a specified DataFrame
Pandas: DataFrame Exercise-36 with Solution
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
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
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.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Join Strings in an Iterable:
>>> words = ('Hello', 'Python', 'Programmers') >>> '!'.join(words) 'Hello!Python!Programmers' >>> words_dict = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'} >>> '&'.join(words_dict.values()) 'zero&one&two&three'
- Exercises: Weekly Top 12 Most Popular Topics
- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion