如何使用scikit-learn通过标准差来规范化数据框?

JP *_*ura 3 python pandas sklearn-pandas

给出以下数据框和left-x列:

|       | left-x | left-y | right-x | right-y |
|-------|--------|--------|---------|---------|
| frame |        |        |         |         |
| 0     | 149    | 181    | 170     | 175     |
| 1     | 149    | 181    | 170     | 175     |
| 2     | 149    | 181    | 170     | 175     |
| 3     | 149    | 181    | 170     | 175     |
Run Code Online (Sandbox Code Playgroud)

如何left-x使用scikit-learn库通过标准偏差进行标准化?

mfi*_*tzp 6

您可以通过标准偏差进行标准化,而无需使用sci-kit-learn,如下所示:

df['left-x'] = df['left-x'] / df['left-x'].std()
Run Code Online (Sandbox Code Playgroud)

或者,如果您还想以数据为中心:

df['left-x'] = (df['left-x'] - df['left-x'].mean())/df['left-x'].std()
Run Code Online (Sandbox Code Playgroud)

df是你的asl.df[l]变量.

.std()方法给出了给定轴上的数据帧的标准偏差.通过首先选择一列,仅为该列计算标准偏差.

如果你需要做很多事情并希望避免混乱,你可以将它包装成一个函数,例如

def std_norm(df, column):
    c = df[column]
    df[column] = (c - c.mean())/c.std()
Run Code Online (Sandbox Code Playgroud)

你称之为:

std_norm(df, 'left-x')
Run Code Online (Sandbox Code Playgroud)

请注意,这会就地更新传递的DataFrame.

  • @JPVentura如果有人会期望它本身就是熊猫(而不是sci-kit),但不是我所知道的.您可以将其包装成一个功能,以便重新使用以降低噪音.我添加了一个例子. (2认同)