第一部分:数据类型处理
数据加载
字段含义:
user_id:用户ID
order_dt:购买日期
order_product:购买产品的数量
order_amount:购买金额
观察数据
查看数据的数据类型
数据中是否储存在缺失值
将order_dt转换为成时间类型
查看数据的统计描述
计算所有用户购买商品的平均数量
计算所有用户购买商品的平均花费
在源数据中添加一列表示月份:astype("datetime64[M]")
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
# 数据的加载
df = pd.read_csv("./data/CDNOW_master-Copy1.txt",header=None, sep='\s+', names=['user_id','order_dt','order_product','order_amount'])
df
user_id order_dt order_product order_amount
0 1 19970101 1 11.77
1 2 19970112 1 12.00
2 2 19970112 5 77.00
3 3 19970102 2 20.76
4 3 19970330 2 20.76
... ... ... ... ...
69654 23568 19970405 4 83.74
69655 23568 19970422 1 14.99
69656 23569 19970325 2 25.74
69657 23570 19970325 3 51.12
69658 23570 19970326 2 42.96
69659 rows × 4 columns
# 查看数据的数据类型
# 数据中是否储存在缺失值
df.info()
# 将order_dt转换为成时间类型
df['order_dt'] = pd.to_datetime(df['order_dt'],format = '%Y%m%d')
df.info()
# 基于order_dt取出其中的月份
df['order_dt'].astype('datetime64[M]')
# 在源数据中添加一列表示月份:astype("datetime64[M]")
df['month'] = df['order_dt'].astype('datetime64[M]')
df.head()
user_id order_dt order_product order_amount month
0 1 1997-01-01 1 11.77 1997-01-01
1 2 1997-01-12 1 12.00 1997-01-01
2 2 1997-01-12 5 77.00 1997-01-01
3 3 1997-01-02 2 20.76 1997-01-01
4 3 1997-03-30 2 20.76 1997-03-01
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 69659 entries, 0 to 69658
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 user_id 69659 non-null int64
1 order_dt 69659 non-null datetime64[ns]
2 order_product 69659 non-null int64
3 order_amount 69659 non-null float64
dtypes: datetime64[ns](1), float64(1), int64(2)
memory usage: 2.1 MB
# 查看数据的统计描述
df.describe()
user_id order_product order_amount
count 69659.000000 69659.000000 69659.000000
mean 11470.854592 2.410040 35.893648
std 6819.904848 2.333924 36.281942
min 1.000000 1.000000 0.000000
25% 5506.000000 1.000000 14.490000
50% 11410.000000 2.000000 25.980000
75% 17273.000000 3.000000 43.700000
max 23570.000000 99.000000 1286.010000
第二部分:按月数据分析
用户每月花费的总金额
绘制曲线图展示
所有用户每月的产品购买量
所有用户每月的消费总次数
统计每月的消费人数
#用户每月花费的总金额
df.groupby(by = 'month')['order_amount'].sum()
#绘制曲线图展示
# plt.plot(df.groupby(by = 'month')['order_amount'].sum())
df.groupby(by = 'month')['order_amount'].sum().plot()
#所有用户每月的产品购买量
df.groupby(by = 'month')['order_product'].sum().plot()
#所有用户每月的消费总次数
df.groupby(by = 'month')['user_id'].count().plot()
#统计每月的消费人数
df.groupby(by = ['month'])['user_id'].nunique().plot() #unique前面加n,nunique表示统计去重后的个数
第三部分:用户个体消费数据分析
用户消费总金额和消费总次数的统计描述
用户消费金额和消费次数的散点图
各个用户消费总金额的直方分布图(消费金额在1000之内的分布)
各个用户消费的总数据的直方分布图(消费商品的数量在100之内的分布)
#用户