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

如何将数据集多bool列转换为单一categorical variables并设置Win分类?

解决方案(基于Python Pandas)

步骤拆解

  • 定位所有布尔类型列(示例中为BoolCol_1至BoolCol_4)
  • 将列值转换为标准布尔值:1替换为True,2替换为False
  • 逐行提取值为True的列名,用分隔符拼接成字符串
  • 统计每行True的数量,若数量等于3,直接将分类设为"Win",否则使用拼接的字符串
  • 将新生成的分类列合并回原数据集

代码实现

import pandas as pd

# 示例数据集
data = {
    "ID": [1, 2],
    "BoolCol_1": [1, 2],
    "BoolCol_2": [2, 1],
    "BoolCol_3": [2, 1],
    "BoolCol_4": [1, 1],
    "Other Col 1": ["x", "A"],
    "Other Col 2": ["Y", "b"]
}
df = pd.DataFrame(data)

# 1. 筛选布尔列
bool_cols = [col for col in df.columns if col.startswith("BoolCol_")]

# 2. 转换为标准布尔值
df_bool = df[bool_cols].replace({1: True, 2: False})

# 3. 拼接True的列名
df["Category"] = df_bool.apply(lambda row: ", ".join(row[row].index), axis=1)

# 4. 判断是否为Win
df["Category"] = df.apply(
    lambda row: "Win" if df_bool.loc[row.name].sum() == 3 else row["Category"],
    axis=1
)

print(df)

输出结果

IDBoolCol_1BoolCol_2BoolCol_3BoolCol_4Other Col 1Other Col 2Category
11221xYBoolCol_1, BoolCol_4
22111AbWin

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:55:20