1

I have a data frame called df_planned and would like to insert into column "order_date" some random dates from Oct-2021. Is there a way to that in the loop? There are 300 rows of the data so obviously the dates can repeat.

I wrote this function to generate the dates:

import datetime
def new(test_date,K):
    res = [test_date + datetime.timedelta(days=idx) for idx in range(K)]
    # printing result
    return(res)

test_date = datetime.datetime(2021, 10, 1)

enter image description here

BENY
  • 317,841
  • 20
  • 164
  • 234

1 Answers1

3

You can use np.random.choice and pd.date_range:

import pandas as pd
import numpy as np

df['order_date'] = np.random.choice(pd.date_range('2021-10-01', '2021-10-31'), 300)
print(df)

# Output:
    order_date
0   2021-10-08
1   2021-10-27
2   2021-10-21
3   2021-10-11
4   2021-10-05
..         ...
295 2021-10-13
296 2021-10-05
297 2021-10-23
298 2021-10-22
299 2021-10-31

[300 rows x 1 columns]

Note: replace 300 by the length of dataframe len(df).

Corralien
  • 109,409
  • 8
  • 28
  • 52