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

Pandas如何根据另一列字符串条件调整对应列数值

Pandas按条件更新列值实现方案

核心实现逻辑

针对「name列值为joe的行,对应wgt列数值乘以1.1」的需求,优先使用pandas原生的loc布尔索引定位+赋值写法,执行效率高、语法规范,不会触发赋值警告。
完整可运行代码:

import pandas as pd

# 构造示例DataFrame
data = {
    'name': ['joe','gary','pete','pete','pete','joe','gary','gary','gary'],
    'wgt': [10,8,12,13,14,11,7,5,7]
}
df = pd.DataFrame(data)

# 按条件更新数值:定位name等于joe的行,对wgt列做乘1.1运算
df.loc[df['name'] == 'joe', 'wgt'] *= 1.1

执行代码后打印df,即可得到预期结果:

namewgt
joe11.0
gary8.0
pete12.0
pete13.0
pete14.0
joe12.1
gary7.0
gary5.0
gary7.0

注意事项

  • 不要使用链式索引写法(例如df[df['name'] == 'joe']['wgt'] = df[df['name'] == 'joe']['wgt'] * 1.1),这种写法会触发SettingWithCopyWarning,且存在赋值不生效的风险。
  • 如果需要保留原始DataFrame、生成新的计算结果,可以使用numpy.where实现:
import numpy as np
df['new_wgt'] = np.where(df['name'] == 'joe', df['wgt'] * 1.1, df['wgt'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 19:09:23