Zack
Zack

Reputation: 349

filtering based on multiple conditions in Python

I have a df which has a list of stocks, index membership, market cap, rank of market cap, turnover and rank of turnover.

i need to created another column called 'Deletes' which will delete stocks based on a few condition.

list of conditions using & and |

  1. the current index membership has to equal DAX and

  2. the market cap rank has to be greater than 35 or

  3. the turnover rank has to be greater than 35

the below code works when the index membership = dax and market cap rank > 35 but does not work when the index membership = dax and turnover > 35. instead it only looks at if the turnover is greater than 35 but not the index membership = dax.

with the below code my result is showing a stock as a delete in the newly created 'deletes' column because its turnover rank is 79 but the index membership is MDAX and not DAX. the first condition has to meet and it is not in this case.

can anyone help me please


df['Deletes'] = np.where((df['Index Membership'] == 'DAX') & (df['MKT Rank'] > 35) | (df['Turnover Rank'] > 35),'delete','')

Upvotes: 0

Views: 90

Answers (1)

jezrael
jezrael

Reputation: 863791

I think here is possible add another () like:

df['Deletes'] = np.where((df['Index Membership'] == 'DAX') & 
                         ((df['MKT Rank'] > 35) | (df['Turnover Rank'] > 35)),'delete','')

because operator precedence.

Upvotes: 3

Related Questions