简体   繁体   中英

How do I check for AND and OR conditions in a python pandas data frame column of type “Array”?

I have created a function to check for each values in the array column of a pandas data frame and then assign values to a new column accordingly. Basically predicting if a diet is healthy based on food intake.

Function I wrote:

Creates a new column called "diet_status" and assigns the value based on values in the column "food_intake" which is of type array.

 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)

How do I check for multiple conditions here? For example, if the "food_intake" array contains "(fruits AND vegetables) AND (chips OR sweets)", I want to name it as "balanced". Need to basically check for AND/OR conditions of values in the array. Could anyone please help me on this.

Because working with scalars here is necessary use or and and , not | and 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM