Modeling_Analysis/code/preprocessing.py

45 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
def load_data(path):
"""加载CSV数据文件支持UTF-8和GBK编码自动检测"""
for enc in ["utf-8", "gbk", "latin-1"]:
try:
return pd.read_csv(path, encoding=enc)
except:
continue
return pd.read_csv(path)
def clean_data(df):
"""清洗数据:删除含缺失值的行,重置索引"""
df = df.dropna().reset_index(drop=True)
return df
def compute_corr_matrix(df):
"""计算相关系数矩阵(排除非数值列)"""
return df.select_dtypes(include=[np.number]).corr()
def detect_outliers(df, col):
"""检测异常值超过99%分位数)"""
threshold = df[col].quantile(0.99)
return df[df[col] > threshold]
def normalize(df, cols):
"""标准化数据列"""
scaler = StandardScaler()
df[cols] = scaler.fit_transform(df[cols])
return df
def split_by_season(df):
"""按季节分割数据"""
seasons = {1: '', 2: '', 3: '', 4: ''}
df['season'] = df['month'].apply(lambda m: seasons.get((m % 12 + 3) // 3, '未知'))
return df
def create_lag_features(df, col, lags):
"""创建滞后特征"""
for lag in lags:
df[f'{col}_lag{lag}'] = df[col].shift(lag)
return df