用标准定标器功能代替手动标准化

Replacing Manual Standardization with Standard Scaler Function

我想用 sklearn 的 StandardScaler 包代替手动计算标准化每月数据。我尝试了注释掉的代码下面的代码行,但收到​​以下错误。

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.

错误消息说 StandardScaler().fit_transform 只接受二维参数。

所以你可以替换:

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

与:

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

作为解决方法。

来自sklearn.preprocessing.scale

Standardize a dataset along any axis

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

所以它应该可以作为标准缩放器使用。