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

如何在DataFrame分组内按条件替换值:组内有r则将nr替换为r

实现代码(基于Pandas)

1. 测试数据构造

import pandas as pd

df = pd.DataFrame({
    'group': ['g1', 'g1', 'g1', 'g1', 'g2', 'g2'],
    'cat_col': ['r', 'nr', 'r', 'nr', 'nr', 'nr']
})

2. 简洁实现方案(适合中小数据集)

直接通过分组transform批量替换:

df['cat_col'] = df.groupby('group')['cat_col'].transform(
    lambda x: 'r' if (x == 'r').any() else x
)

3. 高效实现方案(适合百万级以上大数据集)

先预计算分组映射关系,避免逐分组执行lambda,性能提升明显:

# 生成每个分组是否包含r的映射字典
group_r_map = df.groupby('group')['cat_col'].apply(lambda x: (x == 'r').any()).to_dict()
# 匹配替换
df.loc[df['group'].map(group_r_map), 'cat_col'] = 'r'

输出结果

运行上述代码后得到的df和需求的df_new完全一致:

group cat_col
0    g1       r
1    g1       r
2    g1       r
3    g1       r
4    g2      nr
5    g2      nr

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:45:03