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

如何基于多列OR逻辑在Pandas中创建新列?

Pandas添加ColE列:任意列值为1时ColE为1

你的原始数据集如下:

ColAColBColCColD
1010
0010
1100
1011

可以用以下两种简单方法实现需求:

方法1:使用any()方法

any(axis=1)会逐行检查是否存在真值(这里1等价于True),再通过astype(int)将布尔结果转为1/0:

import pandas as pd

# 构造你的DataFrame
data = {
    'ColA': [1, 0, 1, 1],
    'ColB': [0, 0, 1, 0],
    'ColC': [1, 1, 0, 1],
    'ColD': [0, 0, 0, 1]
}
df = pd.DataFrame(data)

# 添加ColE列
df['ColE'] = df.any(axis=1).astype(int)

方法2:使用sum()方法

由于所有列的值都是0或1,逐行求和后判断是否大于0,再转为整数:

df['ColE'] = (df.sum(axis=1) > 0).astype(int)

执行后得到的结果如下:

ColAColBColCColDColE
10101
00101
11001
10111

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:34:59