I want to fill a numpy array with a fixed datetime64 value. The output should look something like this:
array(['2012-09-01', '2012-09-01', '2012-09-01', '2012-09-01',
'2012-09-01'], dtype='datetime64[D]')
Where the shape of the array and the date value are variable.
Currently I am doing it this way:
shape = (5, )
date = "2012-09"
date_array = np.ones(shape=shape) * np.timedelta64(0, 'D') + np.datetime64(date)
I was wondering if there is a shorter and more readable way to get the same output?
Use numpy.full
:
out = np.full(shape, np.datetime64(date))
# or
out = np.full(shape, date, dtype='datetime64[D]')
Or numpy.tile
:
out = np.tile(np.array(date, dtype='datetime64[D]'), shape)
Or numpy.repeat
and reshape
:
out = np.repeat(np.array(date, dtype='datetime64[D]'),
np.product(shape)).reshape(shape)
NB. for a single dimension np.repeat(np.array(date, dtype='datetime64[D]'), 5)
is enough.
Output:
array(['2012-09-01', '2012-09-01', '2012-09-01', '2012-09-01',
'2012-09-01'], dtype='datetime64[D]')