lundi 1 juin 2020

How to make my nested loops faster in python?

Please, can somebody improve my code, it get the job done, but is very slow.

Every row is match between 2 players, in column "Players" are only the relevant player. I compare a player against the rows before, e.g "Player2" is at index 2, so I only iterate in the rows 0 and 1 My goal is it to find, if a Player has a different "Y in his next match.

df=pd.DataFrame({"Players":["Player1","Player1","Player2","Player1","Player1"],
                 "Win":["Player1","Player4","Player5","Player1","Player6"],
                 "Loss":["Player3","Player1","Player2","Player5","Player1"],
                 "Y": ["B","A","B","B","B"]})


Results=[]
for index, player in enumerate(Players.values, 0):
    Result=[]
    Result.append(0)
    for i in range(df.shape[0]):           
        if index <= df.index.values[i]: #skip the values in the same row
           continue
        if ((player == df.Win.values[i])| (player == df.Loss.values[i])) & (df.Y[index]!=df.Y[i]):  #has previous match a different Y
           Result.append(1)
        elif ((player == df.Win.values[i])| (player == df.Loss.values[i])) & (df.Y[index]==df.Y[i]): #has previous match the same Y       
           Result.append(0)
    Results.append(Result[-1])       

The outpup should look like this:

Results=[0,1,0,1,0]

Aucun commentaire:

Enregistrer un commentaire