Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fill an array with a fixed value of datetime64 data type in NumPy?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading