理论基础知识可以看我之前的博客:
也可以进入我的专栏:欢迎订阅哦,持续更新
文章目录
# 导入库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import warnings
from datetime import datetime
plt.style.use('ggplot') # 画图风格为ggplot 美化
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文字体为黑体,解决图形中不显示中文的问题
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
warnings.filterwarnings("ignore") # 忽略警告
一、数据预处理
数据预处理分为:数据缺失值处理、数据重复值处理、数据异常值处理
1.0、数据格式转化
df = pd.read_csv('data.csv',sep=',',index_col=0) # 读取数据 分割符',' 将第一列作为索引列
df.columns = ['订单时间','订单id','产品id','产品种类id','种类','品牌','价钱','用户id','年龄','性别','地区'] # 修改列名
df.head(2)
订单时间 订单id 产品id 产品种类id 种类 品牌 价钱 用户id 年龄 性别 地区
0 2020-04-24 11:50:39 UTC 2294359932054536986 1515966223509089906 2.268105e+18 electronics.tablet samsung 162.01 1.515916e+18 24.0 女 海南
1 2020-04-24 11:50:39 UTC 2294359932054536986 1515966223509089906 2.268105e+18 electronics.tablet samsung 162.01 1.515916e+18 24.0 女 海南
# 修改字段格式
df['订单id'] = df['订单id'].astype('object')
df['产品id'] = df['产品id'].astype('object')
df['产品种类id'] = df['产品种类id'].astype('object')
df['用户id'] = df['用户id'].astype('object')
df['年龄'] = df['年龄'].astype('int')
df['订单时间'] = df['订单时间'].astype('datetime64')
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 564169 entries, 0 to 2633520
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 订单时间 564169 non-null datetime64[ns]
1 订单id 564169 non-null object
2 产品id 564169 non-null object
3 产品种类id 564169 non-null object
4 种类 434799 non-null object
5 品牌 536945 non-null object
6 价钱 564169 non-null float64
7 用户id 564169 non-null object
8 年龄 564169 non-null int32
9 性别 564169 non-null object
10 地区 564169 non-null object
dtypes: datetime64[ns](1), float64(1), int32(1), object(8)
memory usage: 49.5+ MB
1.1、数据缺失值处理
- 是否删除需要根据数据的重要性判断,如果用不到的字段有缺失,可以将这一列进行删除;如果字段比较重要且缺失值在20%以内也可以删除,若缺失值过多,最好不要删除否则可能会影响结果分析,我们可以看看是否可以通过原数据(的均值、众数等)进行补全;
# 从上面的结果可以知道:总数据有564169条,种类列缺失十万条数据,不能删除;品牌列缺失4万条数据,可以删除
# 缺失较多的用M替补
df['种类'] = df['种类'].fillna('M')
# 缺失较少的直接删除不影响结果
df = df[df['品牌'].notnull()]
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 536945 entries, 0 to 2633520
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 订单时间 536945 non-null datetime64[ns]
1 订单id 536945 non-null object
2 产品id 536945 non-null object
3 产品种类id 536945 non-null object
4 种类 536945 non-null object
5 品牌 536945 non-null object
6 价钱 536945 non-null float64
7 用户id 536945 non-null object
8 年龄 536945 non-null int32
9 性别 536945 non-null object
10 地区 536945 non-null object
dtypes: datetime64[ns](