Pandas - Normalizing data in a DataFrame using a custom function
17. Normalize Data in a DataFrame with a Custom Function
Write a Pandas program that applies a Custom function to Normalize data in a DataFrame.
This exercise demonstrates how to apply a custom function to normalize (scale) the values in a DataFrame.
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({
'A': [10, 20, 30],
'B': [40, 50, 60]
})
# Define a custom function to normalize values
def normalize(column):
return (column - column.min()) / (column.max() - column.min())
# Apply the function column-wise
df_normalized = df.apply(normalize, axis=0)
# Output the result
print(df_normalized)
Output:
A B 0 0.0 0.0 1 0.5 0.5 2 1.0 1.0
Explanation:
- Created a DataFrame with two columns 'A' and 'B'.
- Defined a function normalize() to normalize values by scaling them between 0 and 1.
- Applied the normalization function column-wise using apply() with axis=0.
- Returned a DataFrame with normalized values.
For more Practice: Solve these Related Problems:
- Write a Pandas program to apply a custom normalization function to a numeric column using apply() and then compare the before-and-after statistics.
- Write a Pandas program to use apply() to normalize all numeric columns in a DataFrame using min-max scaling.
- Write a Pandas program to create a custom function that standardizes data and then apply it across the DataFrame using apply().
- Write a Pandas program to compare the performance of a vectorized normalization versus one implemented with apply() and 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.