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

如何对比DataFrame中的值并按条件替换对应列的内容

实现方案

你可以用pandas按以下逻辑实现:

  1. 先提取A列取值为Ex的所有行对应的B列取值集合
  2. 筛选所有B列取值属于上述集合的行,将对应行的C列设为True

完整可运行代码

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame([
    ['Ex', 'Img', False],
    ['Ex', 'Img', False],
    ['Ex2', 'Img', False],
    ['Ex3', 'Img', False],
    ['Ex3', 'Img2', False],
    ['Ex4', 'Img2', False],
    ['Ex5', 'Img3', False]
], columns=['A', 'B', 'C'])

# 提取目标B值
target_b_values = df[df['A'] == 'Ex']['B'].unique()
# 批量更新C列
df.loc[df['B'].isin(target_b_values), 'C'] = True

# 输出结果
print(df)

输出结果

A     B      C
0   Ex   Img   True
1   Ex   Img   True
2  Ex2   Img   True
3  Ex3   Img   True
4  Ex3  Img2  False
5  Ex4  Img2  False
6  Ex5  Img3  False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:57:01