Pandas - Normalizing data in a DataFrame using a custom function
Pandas: Custom Function Exercise-17 with Solution
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.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics