How to scale data between -1 and 1 in pandas

3.5k views Asked by At

enter image description here

enter image description here

Hi guys! Could somebody please help me with this. bh_df is the data set I am working with. As you can see now the data is between approx. 79 and 77. I need to scale it between -1 and 1. Thank you in advance! I wanted to do x_max-x_min thing (advised here https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html), but my min data point is 0, so I do not think it will do anything useful.

1

There are 1 answers

5
Giorgos Myrianthous On BEST ANSWER

To do so, you need a function that transforms your data so that

x_new = (x - min_x)  / (max_x - min_x)

Using pandas

df = df.apply(lambda x:(x-min(x))/(max(x)-min(x)), axis = 0)

Using sklearn.preprocessing.MinMaxScaler

from sklearn.preprocessing import MinMaxScaler


scaler = MinMaxScaler(feature_range=(-1, 1))
normalised_data = scaler.fit_transform(df)

As as side note, if the data is supposed to be fed to a ML model, you should call fit() on training and transform() over test and validation sets.