vendredi 7 juin 2019

How to add a random value to many rows in a Pandas Dataframe iteratively?

Suppose I have a Pandas Dataframe named df, which has the following structure:-

          Column 1 Column 2 ......... Column 104
Row 1      0.01     0.55                 3
Row 2      0.03     0.14                 1
...                       
Row 100    0.75    0.56                  0

What I am trying to accomplish is that for all rows which match the condition given below, I need to generate 100 more rows with a random value between 0 and 0.05 added to each row:-

is_less = df.iloc[:,-1] > 1
df_try = df[is_less]
df = df.append([df_try]*100,ignore_index=True)

The problem is that I can simply duplicate the rows in df_try to generate 100 more rows for each case, but I want to add a random value to each row as well, such that each row is different from the others but very similar.

import random
df = df.append([df_try + random.uniform(0,0.05)]*100, ignore_index=True)

What this does is to simply add the fixed random value to df_try's 100 new rows, but not a unique random value to each row. I know that this is because the above syntax does not iterate over df_try, resulting in the fixed random value being added, but is there a suitable way to add the random values iteratively over the data frame in this case?




Aucun commentaire:

Enregistrer un commentaire