如何使用IF语句对带Pandas的多个条件进行分类

2024-10-01 04:56:22 发布

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

我有分类问题。分类规则是:

如果Storage Condition == 'refrigerate'100 < profit Per Unit < 150Inventory Qty <20 然后restock Action = 'Hold Current stock level'

否则restock Action = 'On Sale'

以下是我需要运行规则的数据集:

ID,Fruit,Stroage Condition,Profit Per Unit,In Season or Not,Inventory Qty,Restock Action
1,Apple ,room temperature ,20,Yes,200,
2,Banana,room temperature ,65,Yes,30,
3,Pear,refrigerate,60,Yes,180,
4,Strawberry,refrigerate,185,No,70,
5,Watermelon ,room temperature ,8,No,90,
6,Mango,Other,20,No,100,
7,DragonFruit,Other,65,No,105,

我尝试过的代码:

for i in range(len(df['ID'])):
    if df['Storage Condition'][i] == 'refrigerate' and df['Profit Per Unit'][i] >100 and df['Profit Per Unit'][i] <150 and df['Inventory Qty'][i]  <20:
        df['restock action'] = 'Hold Current stock level'

but i got this error message: 
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

有人能帮忙吗?谢谢!你知道吗


Tags: andnodfunitactionconditionyesroom
2条回答

如果您不关心性能,那么可以使用一种称为apply的方便方法。它可以接受您的函数并将其应用于数据帧中的行或列。你知道吗

如果你打算学习更多关于熊猫图书馆的知识,了解它的工作原理和使用它的缺点是很好的。你知道吗

When should I ever want to use pandas apply() in my code?

def func(df):
    if df['Stroage Condition'] == 'refrigerate' and 100 < df['Profit Per Unit'] < 150 and df['Inventory Qty'] < 20:
        return 'Hold Current stock level'
    else:
        return 'On Sale'

df['Restock Action'] = df.apply(func, axis='columns')

使用np.where

c1=df['Stroage Condition'].eq('refrigerate')
c2=df['Profit Per Unit'].between(100,150)
c3=df['Inventory Qty']<20
df['Restock Action']=np.where(c1&c2&c3,'Hold Current stock level','On Sale')
print(df)

   ID        Fruit Stroage Condition  Profit Per Unit   In Season or Not  Inventory Qty  \
0   1        Apple  room temperature               20                Yes           200   
1   2       Banana  room temperature               65                Yes            30   
2   3         Pear       refrigerate               60                Yes           180   
3   4   Strawberry       refrigerate              185                 No            70   
4   5   Watermelon  room temperature                8                 No            90   
5   6        Mango             Other               20                 No           100   
6   7  DragonFruit             Other               65                 No           105   

  Restock Action  
0        On Sale  
1        On Sale  
2        On Sale  
3        On Sale  
4        On Sale  
5        On Sale  
6        On Sale  

在这种情况下,没有行验证这3个条件,因此对于所有行,结果都在销售中

相关问题 更多 >