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

Pandas如何按多条件新增列:两列相等且第三列为True时返回布尔值

Pandas 按规则新增Four列的实现方法

实现思路

  • 先统一Three列的数据类型为布尔型,避免示例中字符串格式的真假值导致判断错误
  • 可以选择两种逻辑实现:要么先给Four列默认赋值为空值再修改符合条件的行,要么用多条件匹配一次性完成赋值

完整可运行代码

import pandas as pd
import numpy as np

# 构造示例输入数据
data = [['True', 0,0], ['True', 0, 1], ['False', 0, 1]]
df = pd.DataFrame(data, columns = ['One', 'Two', 'Three'])

# 把Three列从字符串转为布尔类型(如果你的数据中Three列本身就是布尔型可以跳过这一步)
df['Three'] = df['Three'].astype('bool')

# 按规则生成Four列,此处用多条件匹配写法更直观
conditions = [
    (df['Three'] == True) & (df['One'] == df['Two']),
    (df['Three'] == True) & (df['One'] != df['Two']),
    (df['Three'] == False)
]
values = [True, False, pd.NA]
df['Four'] = np.select(conditions, values, default=pd.NA)

# 输出结果
print(df)

输出结果

One  Two  Three   Four
0   True    0   True   True
1   True    1   True  False
2  False    1  False   <NA>

输出中的<NA>就是Pandas内置的空值格式,和需求中的Na语义完全一致,如果需要显示为Na字符串,可以额外增加df['Four'] = df['Four'].astype('str').replace('<NA>', 'Na')处理。

内容的提问来源于stack exchange,提问作者Manolo Dominguez Becerra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:57:03