# Min-max normalization in Python

Learn min-max normalization in Python. Scale features to a set range with NumPy, pandas, and scikit-learn, plus fit_transform for training data.

Min-max normalization rescales numeric data to a fixed range, often between 0 and 1. Python offers simple ways to apply it with NumPy, pandas, or scikit-learn. The method subtracts the column minimum and divides by the column range. 

- Min-max normalization maps each value to the range from 0 to 1.
- The formula is (value - column minimum) divided by (column maximum - column minimum).
- Use MinMaxScaler from scikit-learn for machine learning pipelines.
- Fit the scaler only on training data to avoid data leakage.
- Pandas and NumPy let you implement normalization without extra libraries.
 

## What Min-Max Normalization Does 

Min-max normalization adjusts the scale of numeric features. It subtracts the minimum value of a column from each entry. Then it divides the result by the range of that column. 

The range is the maximum value minus the minimum value. After transformation, every value falls between 0 and 1. The lowest original value becomes 0 and the highest becomes 1. 

The formula is straightforward: normalized value equals original value minus column minimum, divided by column range. This method preserves the shape of the original distribution. It only changes the scale of the numbers. 

## Why Use Min-Max Normalization 

Many machine learning algorithms perform better when features share a similar scale. Gradient descent converges faster with normalized inputs. Distance-based models like k-nearest neighbors do not let large-scale features dominate. 

Normalization also makes comparisons across different units possible. A model can weigh temperature and price fairly. That matters when you bring together attributes from different listings. 

Min-max scaling is a straightforward technique with few parameters to set. It works well when you know the feature distribution is not Gaussian. Other scaling methods may be more appropriate for data with many outliers. 

## Normalize with Pandas 

Pandas DataFrame columns can be normalized with simple arithmetic. Compute the minimum and maximum of a column. Then apply the formula element by element. 

For example, take a DataFrame with a column named price. The code looks like this: df['price_norm'] = (df['price'] - df['price'].min()) / (df['price'].max() - df['price'].min()). This creates a new column with scaled values. 

Pandas is convenient when you explore data in a notebook. It gives you immediate visibility into the before and after values. No extra library import is needed beyond pandas itself. 

## Normalize with NumPy 

NumPy arrays can be normalized across rows or columns. Use np.min and np.max with an axis parameter. The formula is the same difference over range. 

Suppose you have a 2D array where each column is a feature. Then you can do: normalized = (arr - arr.min(axis=0)) / (arr.max(axis=0) - arr.min(axis=0)). This applies min-max scaling column-wise. 

NumPy is fast for large numerical datasets. It works outside the pandas environment. Many preprocessing tasks start with a NumPy array from a CSV or database. 

## Use MinMaxScaler from Scikit-Learn 

Scikit-learn provides a MinMaxScaler class in its preprocessing module. It implements min-max normalization with a familiar fit and transform interface. This is helpful when building a machine learning pipeline. 

First, create an instance with MinMaxScaler(). Then call the fit_transform method on your training data. It returns a scaled array with values between 0 and 1 by default. 

You can change the feature range with the feature_range parameter. Setting feature_range=(0, 2) scales values to the range from 0 to 2. The scaler stores the minimum and range for later use on new data. 

## Fit Only on Training Data 

When you prepare data for machine learning, fit the scaler on training data only. Then use the same scaler to transform validation and test sets. This prevents information from leaking into the model evaluation. 

The method is simple: scaler.fit(train_data) learns the minimum and range. Then scaler.transform(test_data) applies those values to new data. Never call fit or fit_transform on the test set. 

Data leakage can make a model look better than it really is. The test set should remain unseen until final evaluation. Fitting on the whole dataset before splitting is a mistake to avoid. 

## Handle Edge Cases and Outliers 

Min-max normalization assumes that the minimum and maximum are not equal. If a column has the same value for every row, the range is zero. Division by zero must be handled before scaling. 

Outliers strongly affect min-max scaling. One extreme value can compress the rest of the data into a tiny interval. Consider removing or clipping outliers before normalization. 

The scaled range is fixed regardless of the original distribution. A feature with high variance is treated the same as a low variance feature. That may not suit every model or dataset. 

## Compare Scaling Methods 

Min-max normalization is not the only way to scale features. Standardization subtracts the mean and divides by the standard deviation. That centers the data around zero with unit variance. 

Standardization does not bound values to a fixed range. Min-max normalization guarantees a range but is sensitive to outliers. Robust scaling uses the median and interquartile range. 

Your choice depends on the data and the algorithm. Neural networks often benefit from min-max scaling to a small interval. Linear models may work better with standardized features. 

- Min-max: range 0 to 1, sensitive to outliers
- Standardization: mean 0, standard deviation 1
- Robust scaling: median 0, IQR 1, outlier resistant
- No scaling: raw values, may hurt model performance
 

## Min-Max Normalization Questions 

### What is min-max normalization? 

Min-max normalization is a technique that rescales numeric data to a fixed range. It subtracts the minimum value from each data point and divides by the range. The result is a new value between 0 and 1. 

### How do I normalize data in Python? 

You can normalize data in Python using pandas, NumPy, or scikit-learn. For a pandas column, apply the formula (value - min) / (max - min). For machine learning, use MinMaxScaler with fit_transform. 

### Why fit the scaler only on training data? 

The scaler must learn the minimum and maximum from the training data only. Using test data to fit the scaler causes data leakage. That makes your model evaluation overly optimistic. 

### When should I use min-max normalization? 

Use min-max normalization when your features need a consistent scale. It is helpful for distance-based models and neural networks. Consider other methods if your data contains many outliers. 

### What is the difference between normalization and standardization? 

Normalization rescales data to a fixed range like 0 to 1. Standardization centers data to mean 0 and standard deviation 1. Normalization is sensitive to outliers; standardization is more robust.
