在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'])
# 創(chuàng)建新特征(可以根據實際情況選擇合適的方法)
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))
根據需要,可以修改腳本中的數據文件名、列名和模型參數等。