Skip to content
Advertisement

Pandas append row based on conditional sum in long form

So, I have some sample data as such:

JavaScript

which gives a dataframe in long form like:

JavaScript

I want to, for each pair/grouping of location and time, conditionally sum the value column based on the value in the fruit column. Specifically:

I want to sum the apple and orange but NOT the banana rows for each grouping.

Resulting in the below dataframe, with the new rows as specified

JavaScript

Any help is greatly appreciated

Advertisement

Answer

If the condition is the same for each group, just filter first then group by:

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