w3resource

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


16. Fill Missing Values with Custom Function Using apply()

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to fill missing values in a DataFrame column by applying a custom function with apply() that returns the column mean.
  • Write a Pandas program to use apply() to impute missing values in each column based on a custom rule (e.g., forward fill or interpolation).
  • Write a Pandas program to apply a function via apply() that replaces NaN values with a computed statistic for that column.
  • Write a Pandas program to create a custom imputation function and apply it to a DataFrame to fill missing data conditionally.

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.