0

Just Convert R Code into equivalent Python code.

Item_Type - Old Column Name Item_Type_new - New Column Name

perishable = c("Breads", "Breakfast", "Dairy", "Fruits and Vegetables", "Meat", "Seafood")

non_perishable = c("Baking Goods", "Canned", "Frozen Foods", "Hard Drinks", "Health and Hygiene", "Household", "Soft Drinks")

# create a new feature 'Item_Type_new'
combi[,Item_Type_new := ifelse(Item_Type %in% perishable, "perishable", ifelse(Item_Type %in% non_perishable, "non_perishable", "not_sure"))]
0

2 Answers 2

2

With a simple function, you can apply on pandas dataframe:

def func(x, l1, l2):
    """
    x = input value
    l1 = list of perishables
    l2 = list of non-perishables
    """    
    if x in l1:
        return 'perishable'
    elif x in l2:
        return 'non-perishable'
    else:
        return 'not_sure'


perishable = ["Breads", "Breakfast", "Dairy", "Fruits and Vegetables", "Meat", "Seafood"]
non_perishable = ["Baking Goods", "Canned", "Frozen Foods", "Hard Drinks", "Health and Hygiene", "Household", "Soft Drinks"]

combi['Item_Type_new'] = combi.apply(lambda x: func(x, perishable, non_perishable), axis=1)
Sign up to request clarification or add additional context in comments.

Comments

0

Use np.select() -

perishable = ["Breads", "Breakfast", "Dairy", "Fruits and Vegetables", "Meat", "Seafood"]

non_perishable = ["Baking Goods", "Canned", "Frozen Foods", "Hard Drinks", "Health and Hygiene", "Household", "Soft Drinks"]

conditions = [
    (combi['Item_Type'].isin(perishable)),
    (combi['Item_Type'].isin(non_perishable))]

choices = ['perishable', 'non_perishable']

combi['Item_Type_new'] = np.select(conditions, choices, default='non_perishable')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.