【数据挖掘】数据采集和预处理
题目内容:
获取数据并进行基本的预处理操作
我这里选用了2006年至2016年1000部IMDB电影数据集
代码如下
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
import matplotlib.pyplot as plt# 加载数据集
df = pd.read_csv('IMDB-Movie-Data.csv')# 查看数据基本信息
print("数据形状:", df.shape)
print("\n前5行数据:")
print(df.head())
print("\n数据基本信息:")
print(df.info())# 检查缺失值
print("缺失值统计:")
print(df.isnull().sum())# 处理缺失值
# Revenue用中位数填充
df['Revenue (Millions)'].fillna(df['Revenue (Millions)'].median(), inplace=True)
# Metascore用均值填充
df['Metascore'].fillna(df['Metascore'].mean(), inplace=True)print("\n处理后缺失值统计:")
print(df.isnull().sum())# 检查重复值
print("重复值数量:", df.duplicated().sum())# 检查标题重复(可能有重名电影)
print("标题重复数量:", df['Title'].duplicated().sum())# 将Revenue和Metascore转换为float类型
df['Revenue (Millions)'] = df['Revenue (Millions)'].astype(float)
df['Metascore'] = df['Metascore'].astype(float)# 提取年份中的 decade 信息
df['Decade'] = (df['Year'] // 10 * 10).astype(int)# 从Genre列提取第一个类型作为主类型
df['Main_Genre'] = df['Genre'].apply(lambda x: x.split(',')[0])# 从Actors列提取主演数量
df['Actors_Count'] = df['Actors'].apply(lambda x: len(x.split(',')))# 创建高收入标志(收入高于75%分位数)
revenue_75 = df['Revenue (Millions)'].quantile(0.75)
df['High_Revenue'] = df['Revenue (Millions)'].apply(lambda x: 1 if x >= revenue_75 else 0)# 检查数值列的异常值
num_cols = ['Runtime (Minutes)', 'Rating', 'Votes', 'Revenue (Millions)', 'Metascore']
print("\n数值列描述统计:")
print(df[num_cols].describe())# 处理Runtime异常值(超过3小时或少于30分钟的电影)
df = df[(df['Runtime (Minutes)'] >= 30) & (df['Runtime (Minutes)'] <= 180)]# 对数值特征进行归一化
scaler = MinMaxScaler()
df[['Rating_Norm', 'Votes_Norm']] = scaler.fit_transform(df[['Rating', 'Votes']])# 查看标准化结果
print("\n标准化结果示例:")
print(df[['Rating', 'Rating_Norm', 'Votes', 'Votes_Norm']].head())# 数值型特征的统计信息
print("\n数值特征描述统计:")
print(df[num_cols].describe())# 类别型特征的统计信息
print("\n电影类型分布:")
print(df['Main_Genre'].value_counts().head(10))# 电影评分与收入关系
plt.figure(figsize=(10, 6))
sns.scatterplot(x='Rating', y='Revenue (Millions)', data=df)
plt.title('电影评分与收入关系')
plt.show()