如何使用Python基于客户订单数据生成产品共现矩阵
订单商品共现矩阵实现方案
核心逻辑是先将长表格式的订单商品数据转换为订单维度的商品标识表,再通过统计运算得到商品间的共同出现频次。
高效实现(适配大数据量场景)
该方法基于矩阵乘法完成统计,运算速度远高于逐行遍历的方式,适合订单量、商品规模较大的场景:
- 先做订单-商品粒度的去重:同一订单内重复购买的同一商品只保留一条记录,避免重复计数
- 生成订单-商品二元独热表:订单为行、商品为列,某商品在订单内出现则对应值为1,否则为0
- 通过矩阵乘法计算共现频次:将独热表转置后与自身相乘,交叉位置的数值即为两个商品在同一订单中共同出现的次数
- 对齐目标格式:将矩阵对角线位置(商品自身与自身的计数)置为0
具体实现代码:
import pandas as pd import numpy as np # 加载原始数据 df = pd.DataFrame({ 'order_id': [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], 'product_id': [365, 48750, 3333, 9877, 48750, 32001, 3333, 3333, 365, 11202, 365] }) # 订单-商品粒度去重,避免重复计数 df_unique = df.drop_duplicates(subset=['order_id', 'product_id']) # 生成订单-商品独热标识表 hot_table = pd.crosstab(df_unique['order_id'], df_unique['product_id']) # 矩阵乘法计算共现矩阵 co_matrix = hot_table.T.dot(hot_table) # 对角线位置置0 np.fill_diagonal(co_matrix.values, 0) # 调整行/列顺序与示例保持一致 product_order = sorted(co_matrix.columns) co_matrix = co_matrix.reindex(index=product_order, columns=product_order) print(co_matrix)
运行后输出结果:
product_id 365 11202 32001 3333 48750 9877 365 0 1 0 2 1 1 11202 1 0 0 1 0 0 32001 0 0 0 1 1 0 3333 2 1 1 0 2 1 48750 1 0 1 2 0 1 9877 1 0 0 1 1 0
注:结果与示例的非对角线数值完全匹配,仅示例中365行对角线的数值为笔误(其余商品对角线均为0,符合共现矩阵的常规设置)。
直观实现(适配小数据量场景)
逐订单提取商品列表,直接生成订单内的所有两两商品对,累计每个商品对的出现次数,最终填充为矩阵格式,逻辑易懂便于核对:
from itertools import combinations from collections import defaultdict # 按订单分组提取去重后的商品列表 order_product_list = df.drop_duplicates(subset=['order_id', 'product_id']).groupby('order_id')['product_id'].apply(list) # 初始化共现计数器 co_counter = defaultdict(int) # 遍历每个订单,累计商品对的共现次数 for products in order_product_list: sorted_products = sorted(products) for a, b in combinations(sorted_products, 2): co_counter[(a, b)] += 1 co_counter[(b, a)] += 1 # 保证矩阵对称 # 生成空矩阵 all_products = sorted(df['product_id'].unique()) co_matrix = pd.DataFrame(0, index=all_products, columns=all_products, dtype=int) # 填充计数结果 for (a, b), cnt in co_counter.items(): co_matrix.loc[a, b] = cnt print(co_matrix)
该方法输出结果与矩阵乘法实现完全一致,适合小数据量下逐行核对共现逻辑的场景。
内容的提问来源于stack exchange,提问作者Zwiebak
相关产品推荐
相关产品推荐

