Pandas按两列groupby统计第三列共享值并优先取更高共享度的实现
Pandas 多列分组统计col3共享度实现方案
需求梳理
你需要实现的逻辑可拆解为:
- 先按col1进行一级分组
- 每个col1分组内,统计每个col3值被多少个不同的col2值共享,记为共享度
- 对每个col2,取其关联的所有col3的最大共享度作为最终计数,最终输出列表长度和col2的唯一值数量一致
代码实现
1. 构造示例DataFrame
import pandas as pd df = pd.DataFrame({ 'col1': ['A']*8, 'col2': ['ID1', 'ID1', 'ID1', 'ID2', 'ID2', 'ID3', 'ID4', 'ID4'], 'col3': [15, 16, 12, 15, 12, 18, 19, 12] })
2. 核心计算逻辑
def get_max_shared_count(col1_group): # 统计当前col1分组下每个col3的共享度(关联的不同col2数量) col3_shared = col1_group.groupby('col3')['col2'].nunique().rename('shared_degree') # 关联共享度到原分组数据 col1_group = col1_group.merge(col3_shared, on='col3') # 每个col2取最大共享度返回 return col1_group.groupby('col2')['shared_degree'].max() # 按col1分组执行计算 result = df.groupby('col1').apply(get_max_shared_count).reset_index()
结果说明
运行后得到的result数据如下:
| col1 | col2 | shared_degree |
|---|---|---|
| A | ID1 | 3 |
| A | ID2 | 3 |
| A | ID3 | 1 |
| A | ID4 | 3 |
- 输出列表长度和col2唯一值数量(4个)一致,值为
[3,3,3,1] - 如果需要去重后的共享度排序结果,执行
list(result['shared_degree'].unique())即可得到你提到的[3,1]
内容的提问来源于stack exchange,提问作者mattmoore_bioinfo
相关产品推荐
相关产品推荐

