MinMaxScaler for a number of columns in a pandas DataFrame

I want to apply MinmaxScaler on a number of pandas DataFrame ‘together’. Meaning that I want the scaler to perform on all data in those columns, not separately on each column.

My DataFrame has 20 columns. I want to apply the scaler on 12 of the columns at the same time. I have already read this. But it does not solve my problem since it acts on each column separately.

>Solution :

IIUC, you want the sklearn scaler to fit and transform multiple columns with the same criteria (in this case min and max definitions). Here is one way you can do this –

  1. You can save the initial shape of the columns and then transform the numpy array of those columns into a 1D array from a 2D array.
  2. Next you can fit your scaler and transform this 1D array
  3. Finally you can use the old shape to reshape the array back into the n columns you need and save them

The advantage of this approach is that this works with any of the sklearn scalers you need to use, MinMaxScaler, StandardScaler etc.

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()

dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],

cols = ['A','B']
old_shape = dfTest[cols].shape #(5,2)

dfTest[cols] = scaler.fit_transform(dfTest[cols].to_numpy().reshape(-1,1)).reshape(old_shape)
          A         B      C
0  0.000000  0.884188    big
1  0.756853  0.926301  small
2  0.764303  0.956992    big
3  0.817143  0.995530  small
4  0.766885  1.000000  small

Leave a Reply