根据多个条件向Python Pandas DataFrame添加新列

时间:2018-03-31 09:55:50

标签: python pandas numpy

我有一个包含各种列的数据集,如下所示:

discount tax total subtotal productid 3.98 1.06 21.06 20 3232 3.98 1.06 21.06 20 3232 3.98 6 106 100 3498 3.98 6 106 100 3743 3.98 6 106 100 3350 3.98 6 106 100 3370 46.49 3.36 66.84 63 695

现在,我需要添加一个新列,并根据以下条件为其指定值01

if:
    discount > 20%
    no tax
    total > 100
then the Class will 1
otherwise it should be 0

我已经完成了一个条件,但我不知道如何在多种条件下完成它。

我已尝试过这里:

df_full['Class'] = df_full['amount'].map(lambda x: 1 if x > 100 else 0)
  

我已经看了所有其他类似的问题,但无法找到解决我问题的方法。我已经尝试了上述所有帖子,但仍然坚持这个错误:

     

TypeError: '>' not supported between instances of 'str' and 'int'

在第一次发布回答的情况下,我尝试过:

df_full['class'] = np.where( ( (df_full['discount'] > 20) & (df_full['tax'] == 0 ) & (df_full['total'] > 100) & df_full['productdiscount'] ) , 1, 0)

2 个答案:

答案 0 :(得分:3)

您可以使用DataFrame.apply在数据框行中应用任意函数。

在您的情况下,您可以定义一个函数:

def conditions(s):
    if (s['discount'] > 20) or (s['tax'] == 0) or (s['total'] > 100):
        return 1
    else:
        return 0

并使用它为您的数据添加新列:

df_full['Class'] = df_full.apply(conditions, axis=1)

答案 1 :(得分:1)

根据您的数据图像来判断discount 20%的含义是不明确的。

但是,你可能会做这样的事情。

df['class'] = 0 # add a class column with 0 as default value

# find all rows that fulfills your conditions and set class to 1
df.loc[(df['discount'] / df['total'] > .2) & # if discount is more than .2 of total 
       (df['tax'] == 0) & # if tax is 0
       (df['total'] > 100), # if total is > 100 
       'class'] = 1 # then set class to 1

请注意,&在此处表示and,如果您希望or改为使用|