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 :
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.
Go to:
Previous: Use map() with Lambda for Custom Function.
Next: Normalize Data in a DataFrame with a Custom Function.
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.