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

如何在Python的Pandas中基于多列值创建Apple_ind标志列

Pandas 创建Apple_ind标志列解决方案

假设你的DataFrame名为df,可以通过以下方式快速生成目标标志列:

代码实现

# 生成Apple_ind标志列
df['Apple_ind'] = df.loc[:, 'Product_1':'Product_6'].isin(['Red Apple', 'Green Apple']).any(axis=1).astype(int)

代码说明

  • df.loc[:, 'Product_1':'Product_6']:定位所有行的Product_1至Product_6列,确保仅检查产品相关字段
  • .isin(['Red Apple', 'Green Apple']):逐单元格判断值是否为目标苹果产品,返回布尔值组成的DataFrame
  • .any(axis=1):按行校验,只要该行存在至少一个匹配项就返回True
  • .astype(int):将布尔值转换为整数(True→1,False→0),得到最终的标志列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:05:00