Pandas - Normalizing data in a DataFrame using Min-Max scaling
Pandas: Data Cleaning and Preprocessing Exercise-6 with Solution
Write a Pandas program that normalizes data with Min-Max scaling.
In this exercise, we have normalized data using min-max scaling, scaling each value to a range between 0 and 1.
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame with numerical values
df = pd.DataFrame({
'Age': [25, 30, 22, 45],
'Salary': [50000, 60000, 70000, 80000]
})
# Apply min-max scaling to normalize the values between 0 and 1
df_normalized = (df - df.min()) / (df.max() - df.min())
# Output the result
print(df_normalized)
Output:
Age Salary 0 0.130435 0.000000 1 0.347826 0.333333 2 0.000000 0.666667 3 1.000000 1.000000
Explanation:
- Created a DataFrame with numerical data.
- Applied min-max scaling to normalize each value between 0 and 1 using the formula (x - min) / (max - min).
- Outputted the normalized DataFrame.
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