How to create a table grouping by multiple conditions from multiple variables


I am trying to get the results from an excel dataset with multiple conditions on a group by function. The conditions I want are to have if my ‘days’ field is less than 91 days and the employee type not equal to contractor then get a count. I have tried

 df[df['days'] < 91].groupby('empType').count()

Unfortunately gives me counts of everything since I am grouping on the empType.
I have this:

id      empType      days
 1      Contractor   54
 2      Employee     83
 3      Employee     61
 4      Intern       32

When I want this:

id      empType      days 
 2     Employee      83
 3     Employee      61
 4     Intern        32
Asked By: That_non_coder



It seems that you’re missing the second condition from your filter. You can add it with the & and enclosing each filter with (). Try this:

df[(df['days'] < 91) & (df['empType'] != "Contractor")].groupby('empType').count()
Answered By: Marcelo Paco
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.