Pandas - Dropping rows with missing data in a DataFrame using dropna()
2. Handling Duplicates in Pandas
Write a Pandas program to drop rows with missing data.
This exercise demonstrates how to drop rows that contain missing values using the dropna() function.
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame with missing values
df = pd.DataFrame({
'Name': ['David', 'Annabel', 'Charlie', None],
'Age': [25, 30, None, 22],
'Salary': [50000, None, 70000, 60000]
})
# Drop rows that have any missing values
df_dropped = df.dropna()
# Output the result
print(df_dropped)
Output:
Name Age Salary 0 David 25.0 50000.0
Explanation:
- Created a DataFrame with missing values.
- Used dropna() to remove rows that have any missing values.
- Displayed the DataFrame with the rows containing missing values dropped.
For more Practice: Solve these Related Problems:
- Write a Pandas program to remove duplicate rows but keep the first occurrence.
- Write a Pandas program to find and count duplicate values in a specific column.
- Write a Pandas program to drop duplicates based on multiple columns.
- Write a Pandas program to mark duplicate rows with a new column.
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.