I have a dataset with two risk model scores and observations that have a certain amount of value. Something like this:

```
import pandas as pd
df = pd.DataFrame(data={'segment':['A','A','A','A','A','A','A','B','B','B','B','B'],
                      'model1':[9,4,5,2,9,7,7,8,8,5,6,3],
                      'model2':[9,8,2,4,6,8,8,7,7,7,4,4],
                      'dollars':[15,10,-5,-7,6,7,-2,5,7,3,-1,-3]},
                      columns=['segment','model1','model2','dollars'])
print df

   segment  model1  model2  dollars
0        A       9       9       15
1        A       4       8       10
2        A       5       2       -5
3        A       2       4       -7
4        A       9       6        6
5        A       7       8        7
6        A       7       8       -2
7        B       8       7        5
8        B       8       7        7
9        B       5       7        3
10       B       6       4       -1
11       B       3       4       -3

```

My goal is to determine the simultaneous risk model thresholds where value is maximized, i.e. a cutoff like `(model1 >= X) & (model2 >= Y)`. The risk-models are both rank-ordered such that higher numbers are lower risk and generally higher value.

I was able to get the desired output using a loop approach:

```
df_sum = df.groupby(by=['segment','model1','model2'])['dollars'].agg(['sum']).rename(columns={'sum':'dollar_sum'}).reset_index()
df_sum.loc[:,'threshold_sum'] = 0

#this loop works but runs very slowly on my large dataframe
#calculate the sum of dollars for each combination of possible model score thresholds
for row in df_sum.itertuples():
    #subset the original df down to just the observations above the given model scores
    df_temp = df[((df['model1'] >= getattr(row,'model1')) & (df['model2'] >= getattr(row,'model2')) & (df['segment'] == getattr(row,'segment')))]
    #calculate the sum and add it back to the dataframe
    df_sum.loc[row.Index,'threshold_sum'] = df_temp['dollars'].sum()

#show the max value for each segment
print df_sum.loc[df_sum.groupby(by=['segment'])['threshold_sum'].idxmax()]

  segment  model1  model2  dollar_sum  threshold_sum
1       A       4       8          10             30
7       B       5       7           3             15

```

The loop runs incredibly slowly as the size of the dataframe increases. I'm sure there's a faster way to do this (maybe using `cumsum()` or numpy), but I'm stumped on what it is. Does anyone have a better way to do it? Ideally any code would be easily extendable to n-many risk models and would output all possible combinations of `threshold_sum` in case I add other optimization criteria down the road.