Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorized year/month/day operations with NumPy datetime64

Tags:

python

numpy

I would like to create vectors of NumPy datetime64 objects from 1-D vectors of years, months, and days, and also go the reverse direction, that is extracting vectors of years, months, or days from a daily datetime64 vector. I'm using NumPy 1.7.0b2.

For example, suppose

years = [1990, 1992, 1995, 1994]
months = [1, 6, 3, 7]
days = [3, 20, 14, 27]

Now I want to create a np.datetime64 vector of length 4 using these years, months, and days. Is there a way without using a Python loop?

Going the other direction, suppose dates is a vector of datatype np.datetime64 and the frequency is daily. Then I would to be able to something like x.DAYS() and get back a vector [3, 20, 14, 27].

like image 821
Abiel Avatar asked Nov 23 '12 20:11

Abiel


1 Answers

import numpy as np
def compose_date(years, months=1, days=1, weeks=None, hours=None, minutes=None,
              seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):
    years = np.asarray(years) - 1970
    months = np.asarray(months) - 1
    days = np.asarray(days) - 1
    types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',
             '<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')
    vals = (years, months, days, weeks, hours, minutes, seconds,
            milliseconds, microseconds, nanoseconds)
    return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)
               if v is not None)

years = [1990, 1992, 1995, 1994]
months = [1, 6, 3, 7]
days = [3, 20, 14, 27]

print(compose_date(years, months, days))

yields

array(['1990-01-03', '1992-06-20', '1995-03-14', '1994-07-27'], dtype='datetime64[D]')
like image 77
unutbu Avatar answered Nov 13 '22 23:11

unutbu