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

如何对比pandas DataFrame指定两列并按判断条件新增结果列

实现代码

import pandas as pd

# 初始化演示数据集
a = [['Jim', '10', '1.2'], ['John', '15', '70'], ['Bob', '8', '5']]
df = pd.DataFrame(a, columns=['Person','one', 'two'])

# 先将one、two列转为数值类型,避免字符串比较出现逻辑错误
df[['one', 'two']] = df[['one', 'two']].apply(pd.to_numeric)

# 逐行比较生成结果:布尔值True对应整数1,False对应整数0
df['Results'] = (df['one'] > df['two']).astype(int)

输出结果

打印df即可得到目标格式:

Person  one   two  Results
0    Jim   10   1.2        1
1   John   15  70.0        0
2    Bob    8   5.0        1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:54:01