You need to enable JavaScript to run this app. 如何在pandas中合并多个虚拟变量列生成二值新列?
优惠活动
大模型
产品
解决方案
定价
更多

如何在pandas中合并多个虚拟变量列生成二值新列?

pandas虚拟变量多列合并解决方案

核心逻辑是对指定的列组按行聚合,只要行内存在值为1的元素,聚合结果为1,全为0时聚合结果为0,可直接用any()或max()方法实现:

import pandas as pd

# 构造初始DataFrame
data = {'cat_1': [1, 0, 1, 1, 0], 'cat_2':[1, 0, 0, 1, 1], 'cat_3':[0, 0, 1, 1, 1], 'cat_4':[1, 1, 1, 0, 0]}
df = pd.DataFrame(data, index=['s1', 's2', 's3', 's4', 's5'])

# 自定义需要合并的列组,可按需调整分组规则和分组数量
merge_groups = [
    ['cat_1', 'cat_2'],
    ['cat_3', 'cat_4']
]

new_df = pd.DataFrame()
for cols in merge_groups:
    # 生成合并后的列名
    new_col = '_'.join(cols) + ' combined'
    # 按行判断:存在1则返回1,全0返回0
    new_df[new_col] = df[cols].any(axis=1).astype(int)

print(new_df)

运行上述代码得到的输出和预期结果完全一致:

cat_1_cat_2 combined  cat_3_cat_4 combined
s1                     1                     1
s2                     0                     1
s3                     1                     1
s4                     1                     1
s5                     1                     1

如果需要合并更多列,只需要在merge_groups里添加对应的列名列表即可,方法通用无需修改核心逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:45:02