在Python中实现pandas中的R scale函数?

7 python numpy pandas

scale大熊猫R 功能的有效等价是多少?例如

newdf <- scale(df)
Run Code Online (Sandbox Code Playgroud)

写在熊猫?是否有优雅的使用方式transform

her*_*rfz 10

缩放在机器学习任务中非常常见,因此它在scikit-learn的preprocessing模块中实现.您可以将pandas DataFrame传递给它的scale方法.

唯一的"问题"是返回的对象不再是DataFrame,而是一个numpy数组; 如果你想将它传递给机器学习模型(例如SVM或逻辑回归),这通常不是一个真正的问题.如果您想保留DataFrame,则需要一些解决方法:

from sklearn.preprocessing import scale
from pandas import DataFrame

newdf = DataFrame(scale(df), index=df.index, columns=df.columns)
Run Code Online (Sandbox Code Playgroud)

另见这里.


Phi*_*oud 7

我不知道R,但是通过阅读文档,它看起来像下面会做的伎俩(虽然稍微不那么一般)

def scale(y, c=True, sc=True):
    x = y.copy()

    if c:
        x -= x.mean()
    if sc and c:
        x /= x.std()
    elif sc:
        x /= np.sqrt(x.pow(2).sum().div(x.count() - 1))
    return x
Run Code Online (Sandbox Code Playgroud)

对于更通用的版本,您可能需要进行一些类型/长度检查.

编辑:在elif sc:子句中添加了分母的解释

来自R docs:

 ... If ‘scale’ is
 ‘TRUE’ then scaling is done by dividing the (centered) columns of
 ‘x’ by their standard deviations if ‘center’ is ‘TRUE’, and the
 root mean square otherwise.  If ‘scale’ is ‘FALSE’, no scaling is
 done.

 The root-mean-square for a (possibly centered) column is defined
 as sqrt(sum(x^2)/(n-1)), where x is a vector of the non-missing
 values and n is the number of non-missing values.  In the case
 ‘center = TRUE’, this is the same as the standard deviation, but
 in general it is not.
Run Code Online (Sandbox Code Playgroud)

该线np.sqrt(x.pow(2).sum().div(x.count() - 1))通过第一个平方x(pow方法)使用定义计算均方根,然后沿行求和,然后除以NaN每列中的非计数(count方法).

作为一个注释,我不仅仅是在居中后计算RMS的原因是因为该std方法要求bottleneck在特殊情况下更快地计算该表达式,在这种特殊情况下,您要计算标准偏差而不是更一般的RMS.

你可以在居中后计算RMS,可能值得一个基准,因为我现在正在写这个我不确定哪个更快,我没有对它进行基准测试.