如何在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
相关产品推荐
相关产品推荐

