Running a For Loop on a pandas dataframe

I have a dataframe with columns that include part_id and transaction_qty that are sorted by the part_id and then the date that the transaction will occur.

I would like to add a column balance that would run logic like the below. But I am not sure how to call the function so it loops through the dataframe.

For row in dataframe (what is the correct syntax here?):

If part_id for this row index == part_id for the row index before:

this row balance = balance of the row index before + transaction_qty of this row index

else balance = transaction_qty of this row

I have a feeling this is far simpler than I’m thinking it is, but I’ve not found anything in the pandas documentation yet that seems to answer the question

I’ve actually managed to solve this myself with a lot more research. This is what I did:

#define a function that will work out the post transaction stock balance
part = numpy.int64(0)
bal = numpy.float64(0)

def balance_calculation(vec):
    global part
    global bal
    
    if vec[0] == part:
        variance = vec[3] + vec[4]
        bal += variance
        part = vec[0]
        return bal
    
    else:
        bal = vec[3] + vec[4]
        part = vec[0]
        return bal
    


#call the function on all rows of the parts_balance
parts_balance['balance'] = parts_balance.apply(balance_calculation, axis=1)