Pandas - Standardizing a DataFrame using a custom function and applymap()
Pandas: Custom Function Exercise-20 with Solution
Write a Pandas program that uses applymap() to Standardize a DataFrame.
In this exercise, we have applied a custom function to standardize all numeric values in a DataFrame using applymap().
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'A': [10, 20, 30],
'B': [5, 15, 25]
})
# Define a custom function to standardize each element (z-score)
def standardize(x, mean, std):
return (x - mean) / std if std != 0 else 0 # Avoid division by zero
# Apply standardization column-wise
df_standardized = df.apply(lambda col: col.apply(standardize, args=(col.mean(), col.std())))
# Output the result
print(df_standardized)
Output:
A B 0 -1.0 -1.0 1 0.0 0.0 2 1.0 1.0
Explanation:
- Column-wise standardization: The function calculates the z-score based on the mean and standard deviation of each column, which is the correct approach for standardizing data.
- Handling division by zero: The condition if std != 0 else 0 ensures that if a column has no variance (standard deviation is zero), the function returns 0 instead of dividing by zero.
- Column-wise apply(): apply() is used to process each column independently and apply the standardization function element-wise.
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.
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-standardize-dataframe-using-a-custom-function-with-applymap.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics