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

如何基于已有DataFrame创建含指定值二进制标记的新DataFrame?

解决方案:基于指定列表生成存在性标记DataFrame

1. 构造示例数据

首先还原你提供的初始DataFrame:

import pandas as pd

df = pd.DataFrame({
    'ID': [1, 2],
    'SampleColumn1': ['sample Apple', 'sample Cherry'],
    'SampleColumn2': ['sample Cherry', 'sample lemon'],
    'SampleColumn3': ['sample Lime', 'sample Grape'],
    'SampleColumn4': ['sample Apple', 'sample Cherry']
})

指定需要检查的目标水果列表:

target_fruits = ['Apple', 'Lime', 'Cherry', 'Guava', 'Pear']

2. 核心实现代码

通过向量化操作高效完成需求,避免逻辑错误:

# 提取除ID外的列用于检查水果存在性
check_columns = df.drop('ID', axis=1)

# 初始化结果DataFrame,保留ID列
result_df = df[['ID']].copy()

# 遍历每个目标水果,生成对应标记列
for fruit in target_fruits:
    # 检查每行任意列是否包含当前水果,结果转1/0
    result_df[fruit] = (
        check_columns.apply(lambda col: col.str.contains(fruit, na=False), axis=0)
        .any(axis=1)
        .astype(int)
    )

3. 输出结果

运行上述代码后,result_df将完全符合你的期望:

ID  Apple  Lime  Cherry  Guava  Pear
0   1      1     1       1      0     0
1   2      0     0       1      0     0

关键逻辑说明

  • col.str.contains(fruit, na=False):检查单列每个单元格是否包含目标水果,na=False避免空值引发错误
  • .any(axis=1):判断该行任意列是否满足条件(只要有一列包含水果则为真)
  • .astype(int):将布尔值(True/False)转换为1/0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:20:46