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

如何使用np.where实现多列批量修改与新增列的条件操作?

实现多列修改与新增列的方案

首先纠正你现有代码的两个问题:

  • 条件判断要用==而非=,=是赋值操作
  • 你的DataFrame中a是数值型(99.00),不要用字符串'99'做比较,直接用数值99

方案一:用df.loc批量修改 + np.where新增列(高效直观)

这种方式适合数据量较大的场景,定位条件行后批量修改列,再用np.where生成新增列:

import pandas as pd
import numpy as np

# 构造示例DataFrame
df = pd.DataFrame({
    'a': [99.00, 100.00, 99.00],
    'b': [100.00, 102.00, 98.00],
    'c': [100.00, 103.00, 97.00],
    'd': [98.00, 100.00, 96.00]
})

# 定义条件
cond = df['a'] == 99

# 批量修改b、c、d列
df.loc[cond, ['b', 'c', 'd']] = [101.77, 101.96, 99.68]

# 新增列e和f:满足条件时计算对应值,否则设为NaN
df['e'] = np.where(cond, df['b'] + df['c'], np.nan)
df['f'] = np.where(cond, df['b'] + df['c'] + df['d'], np.nan)

方案二:全程用np.where逐列处理

如果你更倾向于用np.where完成所有操作,可以逐列对原有列进行替换,再生成新增列:

# 修改b列:满足条件设为101.77,否则保留原值
df['b'] = np.where(cond, 101.77, df['b'])
# 修改c列
df['c'] = np.where(cond, 101.96, df['c'])
# 修改d列
df['d'] = np.where(cond, 99.68, df['d'])

# 新增e、f列
df['e'] = np.where(cond, df['b'] + df['c'], np.nan)
df['f'] = np.where(cond, df['b'] + df['c'] + df['d'], np.nan)

关键说明

  • 批量修改列时,df.loc[cond, cols]比多次调用np.where效率更高,因为它只需要一次定位条件行
  • 新增列时,np.where可以灵活控制满足/不满足条件时的取值,你可以把np.nan换成你需要的默认值(比如0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:53:09