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

如何在Pandas中按值条件拼接列名生成新列?

实现拼接符合条件列名的解决方案

针对你的需求,我们可以通过两种实用方式创建Keyword列,把每行中值为"1"(或大于0)的列名拼接起来:


方法一:逐行遍历(简单直观)

这种方法代码可读性强,适合小型数据集,用apply函数逐行处理:

首先初始化数据集:

import pandas as pd

data = {'Environment': ['0', '0', '0'], 'Health': ['1', '0', '1'], 'Labor': ['1', '1', '1'], }
df = pd.DataFrame(data, columns=['Environment', 'Health', 'Labor'])

然后添加Keyword列:

# 原数据的值是字符串类型,直接判断是否为"1"
df['Keyword'] = df.apply(
    lambda row: ', '.join(col for col in df.columns if row[col] == '1'),
    axis=1  # axis=1表示按行处理
)

如果后续数据可能转为整数类型,也可以先转换再判断大于0:

df_int = df.astype(int)
df['Keyword'] = df_int.apply(
    lambda row: ', '.join(col for col in df_int.columns if row[col] > 0),
    axis=1
)

方法二:向量化操作(高效性能)

如果数据集较大,推荐使用向量化方法,避免逐行遍历的性能损耗:

# 先将数据转为整数类型,生成布尔掩码
mask = df.astype(int) > 0
# 通过点积拼接列名,再去除末尾多余的", "
df['Keyword'] = mask.dot(df.columns + ', ').str.rstrip(', ')

验证结果

运行上述代码后,打印df就能得到你预期的结果:

Environment Health Labor         Keyword
0           0      1     1  Health, Labor
1           0      0     1           Labor
2           0      1     1  Health, Labor

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:22:52