Sorry if the title is a bit confusing. I really lack my way with words to describe specific pandas challenges. The question can be illustrated with examples below:
I have a dataframe with 3 fields:
import pandas as pd
q =pd.DataFrame({'OrderID':['a1', 'a1','a1','a2', 'a3'],
'Execution_Size': [20, 75, 500, 200, 1000],
'Quote_Size': [300, 300, 300, 500, 600] })
It looks like this:
The group is divided by each order ID value. There is one quote_size corresponding to each unique OrderID. The second column is the one I'm trying to modify, the execution size.
I've done several steps of processing to make sure that regardless of whether the sum of execution_size of each group is bigger than its quote size, the group will stop at the last row or the row that makes the cumsum of execution size bigger than quote size.
For instance, here in the first group, the first rows add up to 95 < 300, the quote size, while the last row makes the cumsum bigger than 300.
What I desired is:
Basically for each group of rows with the same OrderID:
- if there are multiple rows, and the sum of the execution size of the group is bigger than the quote size, make the execution size value in the last row of the group equal (quote_size - (sum of all the rows in the group but the last row)
Using the example here, the third row of Execution_Size shall be 300 - (20 + 75) = 205
- if the sum of execution of the group is smaller than the quote, nothing needs to be done regardless of the number of rows.
- if there is only one execution size for an order ID, and it's bigger than the quote size. Change the value to quote size.
Here the last row: 1000 > 600. Therefore the result is 600.
Thanks for your time in advance. Any advice is appreciated.

