0

Looking for an efficient way to do multi-condition filter (better not iterating through each row).

Original Data:

fruit      price  qty   comment
apple       1.5   10    In Stock
apple       0.7   20    In Stock
pear        3.0   5     In Stock
pear        2.0   5     In Stock 
pear        1.2   30    Out Stock

Filer logic:

if fruit = 'apple'  keep price = 1.5
if fruit = 'Pear'   keep qty = 5

expected output:

fruit      price  qty   comment
apple       1.5   10    In Stock
pear        3.0   5     In Stock
pear        2.0   5     In Stock
harvpan
  • 8,571
  • 2
  • 18
  • 36
Xiaowan Wen
  • 135
  • 1
  • 3
  • 12
  • So `df[((df["fruit"]=="apple")&(df["price"]==1.5))|((df["fruit"]=="pear")&(df["qty"]==5))]`? – pault Sep 13 '19 at 18:43
  • Possible duplicate of [Selecting with complex criteria from pandas.DataFrame](https://stackoverflow.com/questions/15315452/selecting-with-complex-criteria-from-pandas-dataframe) – pault Sep 13 '19 at 18:44

1 Answers1

1

You need to create boolean masks with & and then need '|' for both mask merging.

m1 = ((df['fruit']=='apple') & (df['price']==1.5))
m2 = ((df['fruit']=='pear') & (df['qty']==5))
df.loc[m1 | m2]

Output:

   fruit    price   qty comment
0   apple   1.5 10  In Stock
2   pear    3.0 5   In Stock
3   pear    2.0 5   In Stock
harvpan
  • 8,571
  • 2
  • 18
  • 36