Skip to content
Advertisement

Pandas groupby counting values > 0

I have a pandas df of the following format

JavaScript

I am looking to transform it such that I land up with the below result

JavaScript

Essentially for "HIGH_COUNT" and "LOW_COUNT" I want to count the number of occurrences that column was greater than 0, grouped by "MATERIAL". I have tried to do df.groupby(['MATERIAL']).agg<xxx> but I am unsure of the agg function to use here.

Edit:

I used

JavaScript

but this counts even the 0 rows.

Advertisement

Answer

You could create a boolean DataFrame and groupby + sum:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement