w3resource

Pandas - Dropping rows with missing data in a DataFrame using dropna()

Pandas: Data Cleaning and Preprocessing Exercise-2 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-drop-rows-with-missing-data.php