- 是的,如果你觉得它有用,你可以。
- 您可以缩放单个要素。
如果你做这样的事情,你会得到一个错误:
import pandas as pd
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({
"feature1": [1,2,3,4,5],
"feature2": [100, 200, 300, 400, 500],
"feature3": [200, 300, 400, 500, 600],
})
scaler = StandardScaler()
scaler.fit_transform(df["feature1"])
# output
ValueError: Expected 2D array, got 1D array instead:
如果这是单列,您需要额外重塑输入:
scaler = StandardScaler()
scaler.fit_transform(df["feature1"].values.reshape(-1, 1))
# output
array([[-1.41421356],
[-0.70710678],
[ 0. ],
[ 0.70710678],
[ 1.41421356]])
- 您可以使用 ColumnTransformer 对预处理进行分支。
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
df = pd.DataFrame({
"feature1": [1,2,3,4,5],
"feature2": [100, 200, 300, 400, 500],
"feature3": [200, 300, 400, 500, 600],
})
transformers = ColumnTransformer(
transformers=[
("scaling1", MinMaxScaler(), ["feature1"]),
("scaling2", StandardScaler(), ["feature2", "feature3"])
]
)
transformed_df = transformers.fit_transform(df)
transformed
# output
array([[ 0. , -1.41421356, -1.41421356],
[ 0.25 , -0.70710678, -0.70710678],
[ 0.5 , 0. , 0. ],
[ 0.75 , 0.70710678, 0.70710678],
[ 1. , 1.41421356, 1.41421356]])
如果您想例如使用第一个缩放器 (scaling1) 进行逆变换:
scaler_1 = transformers.named_transformers_["scaling1"]
scaler_1.inverse_transform(transformed[:, 0].reshape(-1, 1))
# output
array([[1.],
[2.],
[3.],
[4.],
[5.]])