首页 > 解决方案 > 如何在“Array”类型的 python pandas 数据框列中检查 AND 和 OR 条件?

问题描述

我创建了一个函数来检查熊猫数据框的数组列中的每个值,然后将值相应地分配给新列。基本上根据食物摄入量预测饮食是否健康。

我写的功能:

创建一个名为“diet_status”的新列,并根据数组类型的“food_intake”列中的值分配值。

 def diet(a):
    if 'fruits' in a:
        y = 'healthy'
    elif 'vegetables' in a:
        y = 'healthy'
    elif 'chips' in a:
        y = 'unhealthy'
    elif 'sweets' in a:
        y = 'unhealthy'
    else
        y = 'NA'
    return y 



df["diet_status"] = df["food_intake"].apply(diet)

如何在这里检查多个条件?例如,如果“food_intake”数组包含“(fruits AND vegetables) A​​ND (chips OR sweets)”,我想将其命名为“balanced”。基本上需要检查数组中值的 AND/OR 条件。谁能帮我解决这个问题。

标签: pythonarrayspandasdataframeif-statement

解决方案


因为在这里使用标量是必要的使用orand and, not|和 not &

 def diet(a):

    m1 = ('fruits' in a) or ('vegetables' in a)
    m2 = ('chips' in a) or ('sweets' in a)
    if m1:
        y = 'healthy'

    elif m2: 
        y = 'unhealthy'

    elif m1 and m2:
        y = 'balanced'
        
    else
        y = 'NA'
    return y 

推荐阅读