Optimize a transformation from a 2-dim numpy array with day of the year values (doy) into an array with date values
<p>Does anyone know how to optimize a transformation from a 2-dim numpy array with day of the year values (doy) into 
an array with date values?
The function below works but unfortunately in an very inelegant way. I would be very happy if anyone has a good idea
how to avoid the loop over the 2-dim array which should make the calculation faster for large datesets. </p>

<pre><code>import datetime
from datetime import date

#test 2-dim array with doy values
doy = np.array([[272, 272],
                [274, 274]])

#define start and end date
startdat = datetime.datetime.strptime('2012 10 01 0000', '%Y %m %d %H%M')
year_start = int(startdat.strftime('%Y'))
enddat = datetime.datetime.strptime('2013 09 30 0000', '%Y %m %d %H%M')
year_end = int(enddat.strftime('%Y'))

#initialise an tmp array
res_date = np.zeros([2,2]) 

#transform doy into date    
for x in range(2):
    for y in range(2):
        if doy[x,y] &gt;= 274 and doy[x,y] &lt;= 365:
            datum = date.fromordinal(date(year_start, 1, 1).toordinal() + doy[x,y])
            datum = datum.strftime('%Y%m%d')    
            res_date[x,y]= datum
        else:
            datum = date.fromordinal(date(year_end, 1, 1).toordinal() + doy[x,y])
            datum = datum.strftime('%Y%m%d')    
            res_date[x,y]= datum
#that's my result
#res_date = array([[ 20130930.,  20130930.],
                  #[ 20121001.,  20121001.]])  
</code></pre>

<p>you can do this kind of thing</p>

<pre><code>offset = (datetime.datetime(2013, 9, 30) - datetime.datetime(2012, 12, 31)).days
yearlen = (datetime.datetime(2013, 1, 1) - datetime.datetime(2012, 1, 1)).days
doy[doy &gt;= offset] -= yearlen
dates = np.datetime64('2013-01-01') + doy
</code></pre>

<p>but to extract YMD from the datetime64 values is a bit tricky. The consensus is to use pandas. Why do you need the array to be in that format?</p>

<p>EDIT, I've added the calculation yearlen but I haven't thought through all the permutations, you probably need to check that with a calendar!</p>

<p>Further EDIT. From your next phrasing of the question your doy looks to be simply days from 2011,9,30 (or from 2011,10,1 minus 1). i.e.</p>

<pre><code>import numpy as np
import datetime

#counting the doys from the 1. of October to the 30 of September
doy = np.array([[152, 4],
                [7, 93]])

#read start and enddat
startdat = datetime.datetime(2011,10,1)
dates = np.datetime64(startdat).astype('datetime64[D]') + doy - 1
print(dates)

#array([['2012-02-29', '2011-10-04'],
#      ['2011-10-07', '2012-01-01']], dtype='datetime64[D]')
</code></pre>

python arrays datetime