w3resource

Normalizing numerical data using Min-Max scaling in Pandas


Pandas: Machine Learning Integration Exercise-7 with Solution


Write a Pandas program that normalizes numerical data using Min-Max scaling.

This exercise demonstrates how to normalize numerical features using Min-Max scaling.

Sample Solution :

Code :

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

# Load the dataset
df = pd.read_csv('data.csv')

# Initialize the MinMaxScaler
scaler = MinMaxScaler()

# Apply Min-Max scaling to the 'Age' and 'Salary' columns
df[['Age', 'Salary']] = scaler.fit_transform(df[['Age', 'Salary']])

# Output the scaled dataset
print(df)

Output:

   ID      Name       Age  Gender    Salary  Target
0   1      Sara  0.230769  Female  0.000000       0
1   2    Ophrah  0.615385    Male  0.333333       1
2   3    Torben  0.000000    Male  0.666667       0
3   4  Masaharu  1.000000    Male  1.000000       1
4   5      Kaya       NaN  Female  0.166667       0
5   6   Abaddon  0.538462    Male       NaN       1

Explanation:

  • Loaded the dataset using Pandas.
  • Initialized the MinMaxScaler from Scikit-learn.
  • Applied Min-Max scaling to the 'Age' and 'Salary' columns, transforming them into a range between 0 and 1.
  • Displayed the normalized dataset.

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.