Please help me in replacing a date column of a data frame with random dates between two date (2020-10-01 & 2020-10-31). Below is the sample data for your reference:
stocks = pd.DataFrame({
'ticker':np.repeat( ['aapl','goog','yhoo','msft'], 25 ),
'date':np.tile( pd.date_range('1/1/2011', periods=25, freq='D'), 4 ),
'price':(np.random.randn(100).cumsum() + 10) })
I have tried the below code. However i am not able to implement the code in a dataframe level.
import time
import datetime
import numpy as np
n_rows = 30
start_time = "01/11/2020"
end_time = "30/11/2020"
date2int = lambda s: time.mktime(datetime.datetime.strptime(s,"%d/%m/%Y").timetuple())
int2date = lambda s: datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S')
start_time = date2int(start_time)
end_time = date2int(end_time)
random_ints = np.random.randint(low=start_time, high=end_time, size=(n_rows,1))
random_dates = np.apply_along_axis(int2date, 1, random_ints).reshape(n_rows,1)
print (random_dates)
question from:
https://stackoverflow.com/questions/65842063/how-to-replace-a-date-column-of-a-dataframe-with-a-random-date-between-two-dates 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…