mardi 11 février 2020

Pseudorandomisation with python

I currently have a problem with pseudorandomizing my trials. I am using a while loop in order to create 12 files containing 38 rows (or trials) that match 1 criterion:

1) max color1expl cannot be identical in 3 consecutive rows

Where color1expl is one of the columns in my dataframe.

When I have files of only 38 rows to create, the following script seems to work perfectly.

import pandas as pd

n_dataset_int = 0
n_dataset = str(n_dataset_int)

df_all_possible_trials = pd.read_excel('GroupF' + n_dataset + '.xlsx') # this is my dataset with all possible trials


# creating the files
for iterations in range(0,12): #I need 12 files with pseudorandom combinations

    n_dataset_int += 1 #this keeps track of the number of iterations
    n_dataset = str(n_dataset_int) 

    df_experiment = df_all_possible_trials.sample(n=38) #38 is the total number of trials
    df_experiment.reset_index(drop=True, inplace=True)

    #max color1expl cannot be identical in 3 consecutive trials (maximum in 2 consecutive t.)

    randomized = False

    while not randomized: #thise while loop will make every time a randomization of the rows in the dataframe
        experimental_df_2 = df_experiment.sample(frac=1).reset_index(drop=True) 
        for i in range(0, len(experimental_df_2)):
            try:
                if i == len(experimental_df_2) - 1:
                    randomized = True
                elif (experimental_df_2['color1expl'][i] != experimental_df_2['color1expl'][i+1]) or (experimental_df_2['color1expl'][i] != experimental_df_2['color1expl'][i+2])
                    continue
                elif (experimental_df_2['color1expl'][i] == experimental_df_2['color1expl'][i+1]) and (experimental_df_2['color1expl'][i] == experimental_df_2['color1expl'][i+2]):
                    break    
            except:
                pass

    #export the excel file
    experimental_df_2.to_excel('GroupF_r' + n_dataset + '.xlsx', index=False) #creates a new                                  

However, when doing the same procedure increasing the number from n=38 to n=228, the script seems to run for an indefinite amount of time. So far, more than one day and it did not produce any of the 12 files. Probably because there are too many combinations to try.

Is there a way to improve this script so that it works with a larger amount of rows?




Aucun commentaire:

Enregistrer un commentaire