在Python中,可以使用pandas、numpy等库来处理和分析数据。为了自动化数据清洗过程,可以按照以下步骤进行:
import pandas as pd
import numpy as np
data = pd.read_csv('your_data.csv')
# 查看数据基本信息
print(data.info())
# 处理缺失值
data.dropna(inplace=True) # 删除缺失值所在的行
data.fillna(value, inplace=True) # 用特定值填充缺失值
# 删除重复值
data.drop_duplicates(inplace=True)
# 处理异常值(可以根据实际情况选择合适的方法)
Q1 = data.quantile(0.25)
Q3 = data.quantile(0.75)
IQR = Q3 - Q1
data = data[~((data < (Q1 - 1.5 * IQR)) |(data > (Q3 + 1.5 * IQR))).any(axis=1)]
# 将日期列转换为日期格式
data['date'] = pd.to_datetime(data['date'])
# 对类别变量进行编码
data = pd.get_dummies(data, columns=['category_column'])
# 创建新特征(可以根据实际情况选择合适的方法)
data['new_feature'] = data['feature1'] * data['feature2']
from sklearn.model_selection import train_test_split
X = data.drop('target', axis=1)
y = data['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
from sklearn.preprocessing import StandardScaler, MinMaxScaler
scaler = StandardScaler() # 或使用 MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score, classification_report
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
# 读取数据
data = pd.read_csv('your_data.csv')
# 数据预处理
print(data.info())
data.dropna(inplace=True)
data.drop_duplicates(inplace=True)
Q1 = data.quantile(0.25)
Q3 = data.quantile(0.75)
IQR = Q3 - Q1
data = data[~((data < (Q1 - 1.5 * IQR)) |(data > (Q3 + 1.5 * IQR))).any(axis=1)]
# 数据转换
data['date'] = pd.to_datetime(data['date'])
data = pd.get_dummies(data, columns=['category_column'])
# 特征工程
data['new_feature'] = data['feature1'] * data['feature2']
# 数据分割
X = data.drop('target', axis=1)
y = data['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 训练模型
model = RandomForestClassifier()
model.fit(X_train, y_train)
# 模型评估
y_pred = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
根据需要,可以修改脚本中的数据文件名、列名和模型参数等。