Kaggle 的 Intermediate Machine Learning 的笔记。
2. Missing Values 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any ()] reduced_X_train = X_train.drop(cols_with_missing, axis=1 ) from sklearn.impute import SimpleImputermy_imputer = SimpleImputer() imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train)) imputed_X_valid = pd.DataFrame(my_imputer.transform(X_valid)) imputed_X_train.columns = X_train.columns imputed_X_valid.columns = X_valid.columns for col in cols_with_missing: X_train_plus[col + '_was_missing' ] = X_train_plus[col].isnull() X_valid_plus[col + '_was_missing' ] = X_valid_plus[col].isnull()
3. Categorical Variables 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 drop_X_train = X_train.select_dtypes(exclude=['object' ]) from sklearn.preprocessing import OrdinalEncoderordinal_encoder = OrdinalEncoder() label_X_train[object_cols] = ordinal_encoder.fit_transform(X_train[object_cols]) label_X_valid[object_cols] = ordinal_encoder.transform(X_valid[object_cols]) from sklearn.preprocessing import OneHotEncoderOH_encoder = OneHotEncoder(handle_unknown='ignore' , sparse=False ) OH_cols_train = pd.DataFrame(OH_encoder.fit_transform(X_train[object_cols])) OH_cols_valid = pd.DataFrame(OH_encoder.transform(X_valid[object_cols])) OH_cols_train.index = X_train.index OH_cols_valid.index = X_valid.index