Dany
Dany

Reputation: 63

Counting column values based on values in other columns in Pandas

I am trying to count how many 0 and 1 a student got with pandas in python. For example, I have the following data frame.

+----------------------------------+--------+
|             Students             | Grades |  
+----------------------------------+--------+
| Student1                         |      0 |
| Student1                         |      1 |
| Student1                         |      2 |
| Student2                         |      3 |
| Student2                         |      5 |
| Student2                         |      0 |
| Student3                         |      3 |
| Student3                         |      4 |
| Student3                         |      5 |
+----------------------------------+--------+

As you can see student1 got one grade 0 and one grade 1 totally he got 2. Student2 got only 1 and student3 got 0 (no grade 1 and 0) . I could not figure out how to do it. does anyone know the code to count?

Upvotes: 1

Views: 933

Answers (2)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can try:

>>> df.groupby('Students').agg(lambda x:sum(x.lt(2))).Grades.reset_index(name='Count')
   Students  Counts
0  Student1       2
1  Student2       1
2  Student3       0

References:

  1. df.groupby
  2. series.reset_index
  3. series.lt
  4. df.groupby.agg

Upvotes: 0

anky
anky

Reputation: 75080

You can try creating a boolean column checking if Grades are in [0,1] , then group on Students and take sum.

out = (df['Grades'].isin([0,1]).groupby(df['Students']).sum()
                     .astype(int).reset_index(name='Counts'))

   Students  Counts
0  Student1       2
1  Student2       1
2  Student3       0

Upvotes: 1

Related Questions