w3resource

Filling missing data in a DataFrame using fillna()

Pandas: Data Cleaning and Preprocessing Exercise-1 with Solution

Write a Pandas program to fill missing values (NaN) in a DataFrame using fillna().

In this exercise, you will learn how to fill missing values (NaN) in a DataFrame using fillna() by replacing them with a constant value.

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]
})
# Fill missing values with a constant
df_filled = df.fillna(value={'Name': 'Unknown', 'Age': 0, 'Salary': 0})
# Output the result
print(df_filled)

Output:

      Name   Age   Salary
0    David  25.0  50000.0
1  Annabel  30.0      0.0
2  Charlie   0.0  70000.0
3  Unknown  22.0  60000.0

Explanation:

  • Created a DataFrame with some missing values (None).
  • Used fillna() to fill missing values with constant replacements: 'Unknown' for names, and 0 for missing ages and salaries.
  • Returned the DataFrame with missing values replaced.

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-fill-missing-data-in-a-dataframe-using-fillna.php