【发布时间】:2021-05-25 13:19:09
【问题描述】:
我有以下拆分功能:
from typing import Tuple
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
def split_dataframe(
df: pd.DataFrame,
target_feature: str,
split_ratio: int = 0.2
) -> Tuple[pd.DataFrame, pd.DataFrame, np.ndarray, np.ndarray]:
df_ = df.copy()
X = df_.drop(target_feature, axis=1)
y = df_[target_feature]
encoder = LabelEncoder()
y = encoder.fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = split_ratio)
return X_train, X_test, y_train, y_test
我使用以下方法拆分数据框:
X_train, X_test, y_train, y_test = split_dataframe(df, 'Банк')
我使用管道来转换 X_train 和 y_train
from sklearn.pipeline import Pipeline, FeatureUnion
from mlxtend.feature_selection import ColumnSelector
import category_encoders as ce
cat_pipe = Pipeline(
[
('selector', ColumnSelector(categorical_features)),
('encoder', ce.one_hot.OneHotEncoder())
]
)
num_pipe = Pipeline(
[
('selector', ColumnSelector(numeric_features)),
('scaler', StandardScaler())
]
)
preprocessor = FeatureUnion(
transformer_list=[
('cat', cat_pipe),
('num', num_pipe)
]
)
new_df = pipe.fit_transform(X_train, y_train)
然后我得到 ValueError: A given column is not a column of the dataframe,特别是 KeyError: 'Банк'。我检查了在传递数据帧之前是否存在列以在训练和测试中拆分。如果我将 X = df_.drop(target_feature, axis=1) 删除到 X = df_ 一切正常,但目标功能仍在 X 中。
【问题讨论】:
-
在
onehotencode构造函数中尝试handle_unknown='ignore'。 -
@SayandipDutta 谢谢你的回答。我试过了,还是报错
-
我制作了一个带有名为“Банк”的列的示例数据框,它能够毫无错误地拆分它。请编辑以包含重现错误的
df数据框示例。