Search code examples
pythongroup-bysklearn-pandas

Replacing Manual Standardization with Standard Scaler Function


I want to replace the manual calculation of standardizing the monthly data with the StandardScaler package from sklearn. I tried the line of code below the commented out code, but I am receiving the following error.

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler

arr = pd.DataFrame(np.arange(1,21), columns=['Output'])
arr2 = pd.DataFrame(np.arange(10, 210, 10), columns=['Output2'])
index2 = pd.date_range('20180928 10:00am', periods=20, freq="W")
# index3 = pd.DataFrame(index2, columns=['Date'])
df2 = pd.concat([pd.DataFrame(index2, columns=['Date']), arr, arr2], axis=1)
print(df2)


cols = df2.columns[1:]
# df2_grouped = df2.groupby(['Date'])

df2.set_index('Date', inplace=True)
df2_grouped = df2.groupby(pd.Grouper(freq='M'))

for c in cols:
    #df2[c] = df2_grouped[c].apply(lambda x: (x-x.mean()) / (x.std()))
    df2[c] = df2_grouped[c].apply(lambda x: StandardScaler().fit_transform(x))
print(df2)


ValueError: Expected 2D array, got 1D array instead:
array=[1.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

Solution

  • The error message says that StandardScaler().fit_transform only accept a 2-D argument.

    So you could replace:

    df2[c] = df2_grouped[c].apply(lambda x: StandardScaler().fit_transform(x))
    

    with:

    from sklearn.preprocessing import scale
    df2[c] = df2_grouped[c].transform(lambda x: scale(x.astype(float)))
    

    as a workaround.

    From sklearn.preprocessing.scale:

    Standardize a dataset along any axis

    Center to the mean and component wise scale to unit variance.

    So it should work as a standard scaler.