0

I think it might be a noob question, but I'm new to coding. I used the following code to categorize my data. But I need to command that if, e.g., not all my conditions together fulfill the categories terms, e.g., consider only 4 out of 7 conditions, and give me the mentioned category. How can I do it? I really appreciate any help you can provide.

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)
Ali Ali
  • 101
  • 1
  • 6
  • Referencing this link i used the code from : https://stackoverflow.com/questions/58278691/how-to-use-if-statements-to-categorize-with-multiple-conditions-with-pandas/58278765#58278765 – Ali Ali Dec 27 '20 at 13:35
  • 1
    Check out [this](https://kanoki.org/2020/01/21/pandas-dataframe-filter-with-multiple-conditions) link. It might prove useful. – TheThird Dec 27 '20 at 14:08

1 Answers1

0

Let`s say this is your dataframe:

   Stroage Condition  refrigerate  Profit Per Unit  Inventory Qty
0                  0            1                0             20
1                  1            1              102              1
2                  2            2                5              2
3                  3            0              100              8

and the conditions are the ones you defined:

c1=df['Stroage Condition'].eq(df['refrigerate'])
c2=df['Profit Per Unit'].between(100,150)
c3=df['Inventory Qty']<20

Then you can define a lambda function and pass this to your np.where() function. There you can define how many conditions have to be True. In this example I set the value to at least two.

def my_select(x,y,z):
    return np.array([x,y,z]).sum(axis=0) >= 2

Finally you run one more line:

df['Restock Action']=np.where(my_select(c1,c2,c3), 'Hold Current stock level', 'On Sale')
print(df)

This prints to the console:

   Stroage Condition  refrigerate  Profit Per Unit  Inventory Qty            Restock Action
0                  0            1                0             20                   On Sale
1                  1            1              102              1  Hold Current stock level
2                  2            2                5              2  Hold Current stock level
3                  3            0              100              8  Hold Current stock level

If you have more conditions or rules, you have extend the lambda function with as many variables as rules.

mosc9575
  • 5,618
  • 2
  • 9
  • 32