Pandas统计0/1编码列的组合频次(针对total=2场景)
解决Pandas中按total分组统计多条件两两组合激活次数的问题
问题背景
我在Pandas DataFrame中存储了一组样本,其中多列为0/1编码的条件激活状态。示例代码如下:
import pandas as pd ex = pd.DataFrame({ "cond_1" : [1, 1, 1, 1, 0, 1], "cond_2" : [0, 0, 1, 0, 1, 1], "cond_3" : [0, 1, 0, 1, 1, 1] }) ex = ex.assign(total=ex.sum(axis=1))
生成的DataFrame如下:
| cond_1 | cond_2 | cond_3 | total | |
|---|---|---|---|---|
| 0 | 1 | 0 | 0 | 1 |
| 1 | 1 | 0 | 1 | 2 |
| 2 | 1 | 1 | 0 | 2 |
| 3 | 1 | 0 | 1 | 2 |
| 4 | 0 | 1 | 1 | 2 |
| 5 | 1 | 1 | 1 | 3 |
需要关注total值为2的行,统计各两条件组合的激活次数,目标输出格式如下(两种均可):
目标格式1
| cond_12 | cond_13 | cond_23 | |
|---|---|---|---|
| 2 | 1 | 2 | 1 |
目标格式2(unstack后)
| 组合 | 次数 | |
|---|---|---|
| 0 | cond_12 | 1 |
| 1 | cond_13 | 2 |
| 2 | cond_23 | 1 |
由于条件列较多,需通过groupby按total分组实现统计,该如何操作?
解决方案
1. 提取条件列并生成两两组合
首先分离所有条件列,并用itertools.combinations生成所有两两组合:
import itertools # 提取所有条件列 cond_cols = ex.columns[ex.columns.str.startswith('cond_')] # 生成所有两两条件组合 combos = list(itertools.combinations(cond_cols, 2))
2. 定义分组统计函数
针对每个total分组,统计每个两两组合中两条件同时激活(值为1)的行数:
def count_pairs(group): pair_counts = {} for col1, col2 in combos: # 生成组合名称,如cond_1+cond_2→cond_12 pair_name = f"{col1}{col2[-1]}" # 统计两列同时为1的行数 pair_counts[pair_name] = ((group[col1] == 1) & (group[col2] == 1)).sum() return pd.Series(pair_counts)
3. 执行分组统计
按total分组后应用上述函数,得到格式1的结果:
result = ex.groupby('total').apply(count_pairs)
输出结果:
cond_12 cond_13 cond_23 total 1 0 0 0 2 1 2 1 3 0 0 0
4. 转换为格式2(可选)
如果需要unstack后的格式,过滤total=2的行并整理:
unstacked_result = result.loc[2].reset_index() unstacked_result.columns = ['组合', '次数']
输出结果:
组合 次数 0 cond_12 1 1 cond_13 2 2 cond_23 1
性能说明
该方法适用于大量条件列的场景,itertools.combinations仅生成必要的两两组合,分组统计逻辑逐组计算,内存占用低且效率稳定。
内容的提问来源于stack exchange,提问作者tms
相关产品推荐
相关产品推荐

