0

I have a 3D array with the count of number of days past a benchmark date (e.g., 01.01.2000). I am interested in the actual day-of-year (DOY: 1-365/366)rather than the total number of days past a given date.

For a single value, the below syntax works. For e.g.,

import numpy as np
import datetime

data = 1595
date = datetime.datetime(2000,1,1,0,0) + datetime.timedelta(data -1)
date.timetuple().tm_yday
134

However, I am having issues with using a 3D array.

import numpy as np
import datetime

data = np.random.randint(5, size = (2,2,2))
data = data + 1595
data
array([[[1596, 1595],
    [1599, 1599]],

   [[1596, 1599],
    [1595, 1595]]])

#Function
def Int_to_DOY(int_array):
    date_ = datetime.datetime(2000,1,1,0,0) + datetime.timedelta(int_array - 1)
    return date_.timetuple().tm_yday

doy_data = data * 0 #Empty array

for i in range(2):
    doy_data[:, :, i] = Int_to_DOY(data[:, :, i])

Here is the error message and I am not able to figure this out.

TypeError: unsupported type for timedelta days component: numpy.ndarray

Thanks for your help.

2
  • can you add your expected output? Commented Sep 10, 2019 at 14:02
  • array([[[135, 134], [138, 138]], [[135, 138], [134, 134]]]) Commented Sep 10, 2019 at 14:07

2 Answers 2

1
import numpy as np
import datetime

data = np.random.randint(5, size = (2,2,2))
data = data + 1595

#Function
def Int_to_DOY(int_array):
    date_ = datetime.datetime(2000,1,1,0,0) + datetime.timedelta(int(int_array) -1)
    return date_.timetuple().tm_yday

doy_data = data.flatten()

for i in range(len(doy_data)):
    doy_data[i] = Int_to_DOY(doy_data[i])

doy_data = doy_data.reshape((2,2,2))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the solution and I believe, I was pushing a 2D array wherein it should have been a vector.
1

Since you tagged pandas:

data = np.array([[[1596, 1595],
    [1599, 1599]],

   [[1596, 1599],
    [1595, 1595]]])

s = pd.to_datetime('2000-01-01') + pd.to_timedelta(data.ravel(), unit='D') 
s.dayofyear.values.reshape(data.shape) - 1

Output:

array([[[135, 134],
        [138, 138]],

       [[135, 138],
        [134, 134]]], dtype=int64)

2 Comments

Thank you! I like the pandas approach and something new I learnt today.
Note: On a larger array, pandas is way faster!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.