I'm trying to perform a conditional sum on groups of rows defined by a list of arbitrary column values. By conditional sum, I mean sum values in one column only if the value in a second column is above a threshold. There can be overlap among the groups and the number of elements in each group can be different.
For example, given the following dataframe:
data = {
'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'counter': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'output': [5, 10, 15, 20, 25, 35, 20, 15, 10, 5]
}
df = pd.DataFrame(data)
>>> df
id counter output
0 1 10 5
1 2 9 10
2 3 8 15
3 4 7 20
4 5 6 25
5 6 5 35
6 7 4 20
7 8 3 15
8 9 2 10
9 10 1 5
And the following inputs (I'm flexible if we need to change their format):
group_ids = {'Group A': [1, 2, 3, 4], 'Group B': [6, 7, 8, 9], 'Group C': [4, 5, 6]}
output_threshold = 12
I would like to generate the following new dataframe, which is the sum of counter for each group defined by the list of group_ids only if output exceeds the specified output_threshold. Bonus points if I can add the title to each of these groups:
title sum
Group A 15
Group B 12
Group C 18