Adding random days to timestamp values store in a column and saving results in a new columns

Viewed 52

I have a number of admission dates stored in a column and I would like to add in a new column future random dates (date of discharge) between 3 and 20 days after the day of admission date.

My admission dates:

show = pd.DataFrame(columns=[ 'admission dates'])

show['admission dates'] = random_dates(start=pd.to_datetime('2021-01-01'), 
                                             end=pd.to_datetime('2021-01-31'), size=5)

shows

admission dates
0   2021-01-02
1   2021-01-16
2   2021-01-10
3   2021-01-27
4   2021-01-30

What I am trying to get

admission dates Discharge dates
0   2021-01-02  2021-01-05      # +3
1   2021-01-16  2021-01-26      # +10 
2   2021-01-10  2021-01-15      # +5
3   2021-01-27   ...
4   2021-01-30
2 Answers

We can generate a random integer between 3 and 20 using np.random.randint, then change the dtype of generated integers to timedelta64 and add then with the corresponding values in admission dates

dates = np.random.randint(3, 20, len(show)).astype('timedelta64[D]')
show['discharge date'] = show['admission dates'] + dates

>>> dates
array([14,  9,  6, 16,  6], dtype='timedelta64[D]')

>>> show
  admission dates discharge date
0      2021-01-02     2021-01-16 # + 14 days
1      2021-01-16     2021-01-25 # + 9 days
2      2021-01-10     2021-01-16
3      2021-01-27     2021-02-12
4      2021-01-30     2021-02-05 # + 6 days

You can use:

import random
from datetime import timedelta

show["Discharge dates"] = show["admission dates"] + timedelta(days=random.randint(3, 20))
Related