samedi 21 août 2021

Pandas Fast Alternative to SLOW FOR LOOP

I have a data column with 3 unique items: '1-2 Year', '< 1 Year', '> 2 Years'.

My goal is to transform all the rows to random numbers in months. For example, < 1 year can be any number between 1 and 12 meaning 1 to 12 months. I used a FOR loop but it is running very slow and I am wondering if there is an efficient way to get the task done.

for i in all_data['Age']:
    if i == '1-2 Year':
        all_data['months'] = np.random.randint(12, 24, all_data.shape[0])
    elif i == '< 1 Year':
        all_data['months'] = np.random.randint(1, 12, all_data.shape[0])
    else:
        all_data['months'] = np.random.randint(25, 60, all_data.shape[0])

Above is my code. Please assist with a more efficient way. Thank you.




Aucun commentaire:

Enregistrer un commentaire