MCPcopy Create free account
hub / github.com/Riley702/enhanced_benchmark_tool / preprocess_data

Function preprocess_data

src/data_preprocessing.py:18–62  ·  view source on GitHub ↗

Preprocesses the dataset by handling missing values, scaling numerical features, and encoding categorical features. Args: df (pd.DataFrame): The dataset to preprocess. numerical_features (list): List of numerical feature column names. categorical_features (list)

(df, numerical_features, categorical_features, missing_strategy="mean", scale=True, encode=True)

Source from the content-addressed store, hash-verified

16
17
18def preprocess_data(df, numerical_features, categorical_features, missing_strategy="mean", scale=True, encode=True):
19 """
20 Preprocesses the dataset by handling missing values, scaling numerical features,
21 and encoding categorical features.
22
23 Args:
24 df (pd.DataFrame): The dataset to preprocess.
25 numerical_features (list): List of numerical feature column names.
26 categorical_features (list): List of categorical feature column names.
27 missing_strategy (str): Strategy for imputing missing values ('mean', 'median', or 'most_frequent').
28 scale (bool): Whether to scale numerical features.
29 encode (bool): Whether to encode categorical features.
30
31 Returns:
32 pd.DataFrame: The preprocessed dataset.
33 ColumnTransformer: The fitted transformer for future use.
34 """
35 transformers = []
36
37 # Handle numerical features
38 if numerical_features:
39 num_transformer = []
40 if missing_strategy:
41 num_transformer.append(("imputer", SimpleImputer(strategy=missing_strategy)))
42 if scale:
43 num_transformer.append(("scaler", StandardScaler()))
44 transformers.append(("num", Pipeline(num_transformer), numerical_features))
45
46 # Handle categorical features
47 if categorical_features:
48 cat_transformer = []
49 if missing_strategy:
50 cat_transformer.append(("imputer", SimpleImputer(strategy="most_frequent")))
51 if encode:
52 cat_transformer.append(("encoder", OneHotEncoder(handle_unknown="ignore")))
53 transformers.append(("cat", Pipeline(cat_transformer), categorical_features))
54
55 # Create a column transformer
56 preprocessor = ColumnTransformer(transformers, remainder="passthrough")
57
58 # Apply transformations
59 processed_array = preprocessor.fit_transform(df)
60 processed_df = pd.DataFrame(processed_array, columns=preprocessor.get_feature_names_out())
61
62 return processed_df, preprocessor
63
64
65def detect_outliers_iqr(df, numerical_features, threshold=1.5):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected