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

Pandas DataFrame指定条件下互换列中good、bad取值的实现方法

解决方案

我们假设存储good/bad取值的列名为target_col,使用时替换为你的实际列名即可。

方案1:向量化操作(推荐)

Pandas原生向量化操作性能远高于逐行遍历,不需要写for循环即可实现需求:

# 定义互换的映射关系
swap_dict = {'good': 'bad', 'bad': 'good'}
# 筛选满足othercolumnname >= 100的行,替换目标列取值
condition = df['othercolumnname'] >= 100
df.loc[condition, 'target_col'] = df.loc[condition, 'target_col'].map(swap_dict)

方案2:适配现有for循环逻辑

如果你需要保留原有for循环的写法,直接在判断分支内添加互换逻辑即可:

import numpy as np
for i in np.arange(0, len(df)-1):
    if df.loc[i, 'othercolumnname'] >= 100:
        # 执行互换操作
        current_val = df.loc[i, 'target_col']
        df.loc[i, 'target_col'] = 'bad' if current_val == 'good' else 'good'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:24:01