How to assign random values from a list to a column in a pandas dataframe?

前端 未结 1 522
[愿得一人]
[愿得一人] 2021-01-18 11:54

I am working with Python in Bigquery and have a large dataframe df (circa 7m rows). I also have a list lst that holds some dates (say all days in a given month).

I a

1条回答
  •  孤街浪徒
    2021-01-18 12:53

    Use numpy.random.choice and if necessary convert dates by to_datetime:

    df = pd.DataFrame({
            'A':list('abcdef'),
            'B':[4,5,4,5,5,4],
    })
    
    day_list = pd.to_datetime(['2015-01-02','2016-05-05','2015-08-09'])
    #alternative
    #day_list = pd.DatetimeIndex(['2015-01-02','2016-05-05','2015-08-09'])
    
    df["rand_day"] = np.random.choice(day_list, size=len(df))
    print (df)
       A  B   rand_day
    0  a  4 2016-05-05
    1  b  5 2016-05-05
    2  c  4 2015-08-09
    3  d  5 2015-01-02
    4  e  5 2015-08-09
    5  f  4 2015-08-09
    

    0 讨论(0)
提交回复
热议问题