w3resource

Pandas - Fill missing values in a DataFrame using a custom function


Pandas: Custom Function Exercise-16 with Solution


Write a Pandas program to apply a custom function to fill missing values in a DataFrame.

This exercise shows how to apply a custom function to fill missing values in a DataFrame based on column-specific logic.

Sample Solution :

Code :

import pandas as pd
import numpy as np

# Create a sample DataFrame with missing values
df = pd.DataFrame({
    'A': [1, 2, np.nan],
    'B': [np.nan, 5, 6],
    'C': [7, 8, np.nan]
})

# Define a custom function to fill missing values based on column logic
def fill_missing(x):
    if pd.isna(x):
        return 0  # Fill NaN with 0
    return x

# Apply the function element-wise using applymap()
df_filled = df.applymap(fill_missing)

# Output the result
print(df_filled)

Output:

     A    B    C
0  1.0  0.0  7.0
1  2.0  5.0  8.0
2  0.0  6.0  0.0                                 

Explanation:

  • Created a DataFrame with missing values (NaN).
  • Defined a function fill_missing() that replaces missing values with 0.
  • Applied the function element-wise to the DataFrame using applymap().
  • Returned a DataFrame where all missing values have been filled with 0.

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.



Follow us on Facebook and Twitter for latest update.