Как создать новый столбец, используя условие в Python DataFrame? - PullRequest
0 голосов
/ 02 января 2019

Просто конвертируйте код R в эквивалентный код Python.

Item_Type - старое имя столбца Item_Type_new - имя нового столбца

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"))]

Ответы [ 2 ]

0 голосов
/ 02 января 2019

Использование 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')
0 голосов
/ 02 января 2019

С помощью простой функции вы можете apply на 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...