You need to enable JavaScript to run this app. 如何对Pandas DataFrame逐行做条件判断并更新指定列的值
优惠活动
大模型
产品
解决方案
定价
更多

如何对Pandas DataFrame逐行做条件判断并更新指定列的值

Pandas 条件更新列值解决方案

首先你给出的示例DataFrame中col1和col2的值都是字符串类型,直接做数值大小比较会得到错误结果,需要先将两列转换为数值类型,再做条件更新即可,以下是两种常用实现方式:

  • 方法1:loc条件赋值(优先推荐,直接修改原表无额外开销)
import pandas as pd

# 你的初始DataFrame
df = pd.DataFrame({'col1': ['0','1','2','3','4'],'col2': ['10','20','30','40','50'], 'col3': 0})

# 转换列类型为整数
df['col1'] = df['col1'].astype(int)
df['col2'] = df['col2'].astype(int)

# 匹配双条件后更新col3
df.loc[(df['col1'] < 3) & (df['col2'] > 15), 'col3'] = 1

运行后符合条件的第2行(索引1)、第3行(索引2)的col3会被更新为1,其余行保持原值。

  • 方法2:numpy.where实现(适合多条件分支的赋值场景)
    如果你的场景需要对所有行的col3做全量重写,可以用这个方法:
import pandas as pd
import numpy as np

df = pd.DataFrame({'col1': ['0','1','2','3','4'],'col2': ['10','20','30','40','50'], 'col3': 0})
df['col1'] = df['col1'].astype(int)
df['col2'] = df['col2'].astype(int)

df['col3'] = np.where((df['col1'] < 3) & (df['col2'] > 15), 1, df['col3'])

这里的第三个参数df['col3']表示不满足条件的行保留原有col3的值,如果你需要不满足条件的行统一设为0,直接把第三个参数换成0即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 02:15:01