基于多个条件向Python Pandas数据框添加新列

2024-09-27 00:17:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,包含以下各列:

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

现在,我需要添加一个新的column,并根据以下条件将其赋值为01

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

我用一个单一的条件完成了它,但我不知道如何在多个条件下完成它。

这是我试过的wIat:

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

I have taken a look at all other similar questions but couldn't find any solution for my problem.I have tried all of the above-mentioned posts but stuck on this error:

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)

Tags: ofthe数据dfifhavediscountall
2条回答

根据你的数据图像判断,你所说的discount20%是什么意思还不清楚。

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

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,请使用|

可以使用^{}在数据帧行上应用任意函数。

在您的示例中,可以定义如下函数:

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)

相关问题 更多 >

    热门问题