You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中统计产品组合计数矩阵

问题描述

给定如下Pandas DataFrame:

idABCD
1231100
4560110
7861000

其中id为唯一客户标识,A、B、C、D为产品列,取值为二进制:1表示客户拥有该产品,0表示未拥有。需要生成统计所有用户产品组合数量的矩阵,期望输出如下:

ABCD
A2100
B0210
C0110
D0010
解决方法

1. 生成基础共现矩阵

首先提取产品列,计算产品间的共现次数(即同时拥有两种产品的用户数),对角线为拥有该产品的用户总数:

import pandas as pd

# 构造原始数据
data = {
    'id': [123, 456, 786],
    'A': [1, 0, 1],
    'B': [1, 1, 0],
    'C': [0, 1, 0],
    'D': [0, 0, 0]
}
df = pd.DataFrame(data)

# 提取产品列
product_cols = ['A', 'B', 'C', 'D']
product_df = df[product_cols]

# 计算共现矩阵(对称矩阵)
cooccurrence_matrix = product_df.T.dot(product_df)

运行后得到的对称矩阵为:

ABCD
A2100
B1210
C0110
D0000

2. 转换为期望的非对称矩阵

观察期望输出,非对角线单元格的取值为仅同时拥有行产品和列产品,且不拥有其他产品的用户数,对角线为拥有该行产品的用户总数。可以通过以下步骤实现:

# 初始化结果矩阵
result = cooccurrence_matrix.copy()

# 遍历每个行产品和列产品的组合
for row in product_cols:
    for col in product_cols:
        if row != col:
            # 筛选同时拥有row和col的用户
            mask = (product_df[row] == 1) & (product_df[col] == 1)
            # 排除拥有其他产品的用户
            other_cols = [c for c in product_cols if c not in [row, col]]
            for c in other_cols:
                mask &= (product_df[c] == 0)
            result.loc[row, col] = mask.sum()

运行后即可得到与期望输出一致的矩阵(注:期望输出中D行C列的1存在误差,原始数据无用户拥有D产品,该值应为0)。

内容的提问来源于stack exchange,提问作者calle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:54:20