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

基于指定条件批量更新DataFrame中唯一Id对应所有行的score值

Pandas 按ID批量更新Score字段

问题示例

原始DataFrame

Id           condition1        condition2       score
A               attempt           pass            0
A               attempt           fail            0
B               attempt           pass            0
B               attempt           level_1         0
B               attempt           fail            0
C               attempt           fail            0
D               attempt           fail            0

目标DataFrame

Id           condition1        condition2       score
A               attempt           pass            1
A               attempt           fail            1
B               attempt           pass            1
B               attempt           level_1         1
B               attempt           fail            1
C               attempt           fail            0
D               attempt           fail            0

需求规则

如果某个Id的任意一行满足 condition1 == 'attempt' 且 condition2 == 'pass',则该Id下所有行的score设为1,其余行保持0。

解决方案

用Pandas的筛选+映射即可实现,代码如下:

import pandas as pd

# 初始化示例数据
df = pd.DataFrame({
    'Id': ['A', 'A', 'B', 'B', 'B', 'C', 'D'],
    'condition1': ['attempt'] * 7,
    'condition2': ['pass', 'fail', 'pass', 'level_1', 'fail', 'fail', 'fail'],
    'score': [0] * 7
})

# 提取符合条件的唯一Id集合
qualified_ids = df[(df['condition1'] == 'attempt') & (df['condition2'] == 'pass')]['Id'].unique()

# 更新score列
df['score'] = df['Id'].isin(qualified_ids).astype(int)

# 输出结果
print(df)

代码解释

  1. 筛选达标ID:通过布尔索引找出所有满足条件的行,提取唯一Id存入qualified_ids
  2. 批量更新score:用isin()判断每行Id是否在达标集合中,返回布尔序列后转成整数(True→1,False→0),直接覆盖原score列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:15:32