Spaces:
Paused
Paused
Synced repo using 'sync_with_huggingface' Github Action
Browse files- data/data_preprocessing.py +41 -0
data/data_preprocessing.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from sklearn.impute import SimpleImputer
|
| 3 |
+
from sklearn.preprocessing import LabelEncoder
|
| 4 |
+
|
| 5 |
+
def load_data(file_path):
|
| 6 |
+
"""Load dataset from a CSV file."""
|
| 7 |
+
return pd.read_csv(file_path)
|
| 8 |
+
|
| 9 |
+
def handle_missing_values(df):
|
| 10 |
+
"""Handle missing values in the dataset."""
|
| 11 |
+
# Impute numerical columns with the median
|
| 12 |
+
numerical_cols = df.select_dtypes(include=['float64', 'int64']).columns
|
| 13 |
+
imputer = SimpleImputer(strategy='median')
|
| 14 |
+
df[numerical_cols] = imputer.fit_transform(df[numerical_cols])
|
| 15 |
+
|
| 16 |
+
# Impute categorical columns with the most frequent value
|
| 17 |
+
categorical_cols = df.select_dtypes(include=['object']).columns
|
| 18 |
+
imputer = SimpleImputer(strategy='most_frequent')
|
| 19 |
+
df[categorical_cols] = imputer.fit_transform(df[categorical_cols])
|
| 20 |
+
|
| 21 |
+
return df
|
| 22 |
+
|
| 23 |
+
def encode_categorical_variables(df):
|
| 24 |
+
"""Encode categorical variables using Label Encoding."""
|
| 25 |
+
categorical_cols = df.select_dtypes(include=['object']).columns
|
| 26 |
+
label_encoder = LabelEncoder()
|
| 27 |
+
for col in categorical_cols:
|
| 28 |
+
df[col] = label_encoder.fit_transform(df[col])
|
| 29 |
+
return df
|
| 30 |
+
|
| 31 |
+
def preprocess_data(file_path):
|
| 32 |
+
"""Load, preprocess, and return the dataset."""
|
| 33 |
+
df = load_data(file_path)
|
| 34 |
+
df = handle_missing_values(df)
|
| 35 |
+
df = encode_categorical_variables(df)
|
| 36 |
+
return df
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
file_path = 'path_to_your_data.csv' # Replace with your actual file path
|
| 40 |
+
processed_data = preprocess_data(file_path)
|
| 41 |
+
processed_data.to_csv('processed_data.csv', index=False)
|