Handling Missing Values in DataFrame

Write a Pandas program to find and replace the missing values in a given DataFrame.

Example 1:

Input: DataFrame with some missing values 
Output: DataFrame with missing values replaced

Example 2:

Input: DataFrame with some missing values 
Output: DataFrame with missing values replaced

Use the pandas DataFrame fillna() function.

import pandas as pd
import numpy as np

def replace_missing_values(df, replacement_value):
    return df.fillna(replacement_value)

df1 = pd.DataFrame({'name': ['Tom', 'Jack', 'Steve', np.nan], 'score': [85, np.nan, 87, 91]})
df2 = pd.DataFrame({'name': ['Adam', 'Eve', np.nan, 'Rogers'], 'score': [np.nan, 92, 95, 97]})

print(replace_missing_values(df1, 'Unknown'))
print(replace_missing_values(df2, 'Unknown'))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!