聚合

Python 中的购物篮分析

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

探索数据

import pandas as pd

# 载入礼品数据
gifts = pd.read_csv('datasets/novelty_gifts.csv')

# 用 head() 预览
print(gifts.head())
  InvoiceNo                          Description
0    562583      IVORY STRING CURTAIN WITH POLE 
1    562583        PINK AND BLACK STRING CURTAIN
2    562583                PSYCHEDELIC TILE HOOK
3    562583                ENAMEL COLANDER CREAM
4    562583  SMALL FOLDING SCISSOR(POINTED EDGE)
Python 中的购物篮分析

探索数据

# 打印交易数
print(len(gifts['InvoiceNo'].unique()))
9709
# 打印商品数
print(len(gifts['Description'].unique()))
3461
Python 中的购物篮分析

剪枝与聚合

剪枝 该图显示了一列项目,其中一些被划掉,表示已剪枝。

聚合 该图显示将一列项目映射为更短的列表,表示进行聚合。

Python 中的购物篮分析

聚合数据

# 载入独热编码数据
onehot = pd.read_csv('datasets/online_retail_onehot.csv')

# 预览 DataFrame
print(onehot.head(2))
    50'S CHRISTMAS GIFT BAG LARGE   DOLLY GIRL BEAKER ...  ZINC WILLIE WINKIE  CANDLE STICK
0                           False               False                               False
1                           False               False                               True
Python 中的购物篮分析

聚合数据

# 选择包含 bags 和 boxes 的列名
bag_headers = [i for i in onehot.columns if i.lower().find('bag')>=0]
box_headers = [i for i in onehot.columns if i.lower().find('box')>=0]
# 选取相应列
bags = onehot[bag_headers]
boxes = onehot[box_headers]
print(bags)
       50'S CHRISTMAS GIFT BAG LARGE   RED SPOT GIFT BAG LARGE  
0                              False                     False   
1                              False                     False
...                             ...                      ...
Python 中的购物篮分析

聚合数据

# 按列求和
bags = (bags.sum(axis=1) > 0.0).values
boxes = (boxes.sum(axis=1) > 0.0).values
print(bags)
[False  True False ... False  True False]
Python 中的购物篮分析

聚合数据

# 将结果加入 DataFrame
aggregated = pd.DataFrame(np.vstack([bags, boxes]).T, columns = ['bags', 'boxes'])
print(aggregated.head())
    bags  boxes
0  False  False
1   True  False
2  False  False
3  False  False
4   True  False
Python 中的购物篮分析

用聚合做购物篮分析

  • 聚合流程
    • 商品 -> 类别
    • 计算指标
    • 识别规则
# 计算支持度
print(aggregated.mean())
bags     0.130075
boxes    0.071429
Python 中的购物篮分析

Passons à la pratique !

Python 中的购物篮分析

Preparing Video For Download...