Generate random no of days based on random selection of columns

前端 未结 2 534
情歌与酒
情歌与酒 2021-01-15 09:56

I have a dataframe like as shown below. Thanks to SO community for helping with the below

df1 = pd.DataFrame({\'person_id\': [11,11, 12, 13, 14],
                     


        
相关标签:
2条回答
  • 2021-01-15 10:23

    I would generate random on [0,1] and scale accordingly:

    np.random.seed(10)
    rand = np.random.random(len(df_offset))
    
    df_offset['rand_number'] = (rand * (df_offset.min_days_to_next_year + df_offset.min_days_to_prev_year) 
                                     -  df_offset.min_days_to_prev_year
                               ).astype(int)
    

    Output:

          person_id  dates                  min_days_to_prev_year    min_days_to_next_year    rand_number
    --  -----------  -------------------  -----------------------  -----------------------  -------------
     0           11  1961-12-30 00:00:00                      363                        1            -82
     1           12  1967-05-29 00:00:00                      148                      216           -140
     2           13  1957-01-01 00:00:00                        0                      364            230
     3           14  1959-07-27 00:00:00                      207                      157             65
    
    0 讨论(0)
  • 2021-01-15 10:34

    You can try something like this:

    >>> import random
    >>> rand_numbers = pd.Series(random.randint(*sorted((0, -1*i if random.choice((0,1)) else j))) for i,j in zip(df_offset.min_days_to_prev_year, df_offset.min_days_to_next_year))
    >>> df_offset['rand_numbers'] = rand_numbers
    >>> df_offset
       person_id      dates  min_days_to_prev_year  min_days_to_next_year  rand_numbers
    0         11 1961-12-30                    363                      1          -235
    1         12 1967-05-29                    148                    216           168
    2         13 1957-01-01                      0                    364             2
    3         14 1959-07-27                    207                    157           132
    
    0 讨论(0)
提交回复
热议问题