implementing R scale function in pandas in Python?

numpy, pandas, python

Solution

Scaling is very common in machine learning tasks, so it is implemented in scikit-learn's `preprocessing` module. You can pass pandas DataFrame to its `scale` method.

The only "problem" is that the returned object is no longer a DataFrame, but a numpy array; which is usually not a real issue if you want to pass it to a machine learning model anyway (e.g. SVM or logistic regression). If you want to keep the DataFrame, it would require some workaround:

from sklearn.preprocessing import scale
from pandas import DataFrame

newdf = DataFrame(scale(df), index=df.index, columns=df.columns)

See also here.

Problem

What is the efficient equivalent of R's `scale` function in pandas? E.g. ``` newdf <- scale(df) ``` written in pandas? Is there an elegant way using `transform`?

Original source

Related problems