mardi 25 septembre 2018

How to properly set an increment in a while loop?

i have a dataframe (DF) I need to loop over each row and check if some conditions are met in that row if they are then flag that row (say I add another column labelled "flag" and equalize it to 1)- in the same loop check if there are other rows that have similar conditions, if they do then flag them as well. At the next loop look at the same DF but exclude the flagged rows. The size of the DF will go from NxM to (N-n) x M where n is the number of rows flagged. The loop will go on until the len(DF)is <=1 (meaning until all rows are flagged as 1). The for loop does not work because as the loop goes on the size of DF shrinks so I can only use while loop with increment. However, how can i set the increment ( it should dynamic).

I am really not sure how to tackle this problem.

Here is a failed attempt.

a=len(DF.loc[DF['flag'] != 1]) #should be  (NxM) initially
i = 0
# at every loop we redefine size of DF in variable a
while a >= 1:
        print(i)
        # select first row          
        row = DF.loc[DF['flag'] != 1].iloc[[i]]
        # flag row if conditions are met
        DF['flag'].values[i] = np.where(if conditions met, 1, '')

        #there is another piece of code that looks for rows with similar 
        #conditions but won't add it here

        # the following variable a redefines length of DF 
        a=len(allHoldingsLookUp.loc[allHoldingsLookUp['flag'] != 1])
        i+=1

I have a problem here. the increment i does not work. Say i reaches 100 and the length of DF shrinks to say 70. The increment needs to be set differently but not sure how.

Aucun commentaire:

Enregistrer un commentaire