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

基于条件语句分组数据:按Test_ID1统计生成结果列

解决方案

原始数据

Test_ID1Output
AM
AM
AM
AF
BF
BF
BF
CM
CF

需求说明

按Test_ID1分组统计每组内M和F的出现次数:

  • 若M计数 > F计数,最终输出M
  • 若F计数 > M计数,最终输出F
  • 两者计数相等时,输出P

预期结果

Test_ID1Final_Output
AM
BF
CP

实现代码(Python Pandas)

import pandas as pd

# 构造原始数据
data = {
    'Test_ID1': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
    'Output': ['M', 'M', 'M', 'F', 'F', 'F', 'F', 'M', 'F']
}
df = pd.DataFrame(data)

# 分组统计M和F的数量
counts = df.groupby('Test_ID1')['Output'].value_counts().unstack(fill_value=0)

# 计算Final_Output
counts['Final_Output'] = counts.apply(
    lambda row: 'M' if row['M'] > row['F'] else ('F' if row['F'] > row['M'] else 'P'),
    axis=1
)

# 提取结果并重置索引
result = counts[['Final_Output']].reset_index()
print(result)

代码解释

  1. 先构造包含原始数据的DataFrame;
  2. 使用groupby+value_counts统计每组内M和F的出现次数,通过unstack将结果转为宽表格式,缺失值用0填充;
  3. 用apply遍历每一行,根据计数规则生成Final_Output;
  4. 提取需要的列并重置索引,得到最终结果。

内容的提问来源于stack exchange,提问作者Data-7scientist

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:12:59