w3resource

Pandas - Normalizing data in a DataFrame using Min-Max scaling


6. Normalizing Data with Min-Max Scaling

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to apply Min-Max scaling to a numeric column and store the results in a new column.
  • Write a Pandas program to normalize multiple columns simultaneously using Min-Max scaling.
  • Write a Pandas program to compare original and normalized values by plotting them side-by-side.
  • Write a Pandas program to selectively apply Min-Max scaling only on columns with a specific data type.

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.



Follow us on Facebook and Twitter for latest update.