Amir
Amir

Reputation: 11

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:

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?

Upvotes: 0

Views: 70

Answers (2)

Nin17
Nin17

Reputation: 3472

You can also use numpy.broadcast_to (which is significantly faster if shape is large):

np.broadcast_to(np.datetime64(date, "D"), shape)

Output:

array(['2012-09-01', '2012-09-01', '2012-09-01', '2012-09-01',
       '2012-09-01'], dtype='datetime64[D]')

Timings:

shape = 500, 500

%timeit np.full(shape, np.datetime64(date))
%timeit np.full(shape, date, dtype='datetime64[D]')
%timeit np.tile(np.array(date, dtype='datetime64[D]'), shape)
%timeit np.repeat(np.array(date, dtype='datetime64[D]'), np.product(shape)).reshape(shape)
%timeit np.broadcast_to(np.datetime64(date, "D"), shape)

Output:

35 µs ± 154 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
36.4 µs ± 95.6 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
1.08 ms ± 294 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
807 µs ± 4.9 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
4.21 µs ± 6.31 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

Upvotes: 1

mozway
mozway

Reputation: 260300

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]')

Upvotes: 2

Related Questions