Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

how to replace a date column of a dataframe with a random date between two dates in python

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use pd.Timestamp and random.randint to generate random dates between given dates and use pd.to_datetime() to convert it to date

start = '2020-10-01' # Specify start date
end = '2020-10-31'
n = len(stocks)
x = np.random.randint(pd.Timestamp(start).value, pd.Timestamp(end).value,n, dtype=np.int64)
stocks['date'] = [pd.to_datetime((i/10**9)/(60*60)/24, unit='D').strftime('%Y-%m-%d')  for i in x]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...