Wednesday, 7 April 2021

xarray - apply a function to the time dimension of a DataArray and add the result as a variable

I have a DataArray da with a variable called FFDI which has three dimensions, time, latitude and longitude.

xarray.DataArray   'FFDI'   time: 43848   latitude: 2   longitude: 244

latitude     (latitude)     float32           -39.2 -39.163948
longitude    (longitude)    float32           140.8 140.83786 ... 149.96214 150.0
time         (time)         datetime64[ns]    2000-01-01T00:00:00  2000-01-01T01:00:00  ...  2004-12-31T22:00:00  2004-12-31T23:00:00

What I want to achieve is to apply the following function to each timestamp of the time dimension to calculate if the timestamp is during the Daylight Savings period and the output a boolean.

def isDST(dt_str):
    local_time_tz = pytz.timezone("Australia/Victoria")
    naive_datetime = datetime.datetime.strptime (dt_str, "%Y-%m-%d %H:%M:%S")
    a = local_time_tz.localize(naive_datetime)
    return bool(a.dst())

The output would be an numpy array or another DataArray element; then it would be added to the original da as additional variable named isDST.

xarray.DataArray   'FFDI'   time: 43848   latitude: 2   longitude: 244

latitude     (latitude)     float32           -39.2 -39.163948
longitude    (longitude)    float32           140.8 140.83786 ... 149.96214 150.0
time         (time)         datetime64[ns]    2000-01-01T00:00:00  2000-01-01T01:00:00  ...  2004-12-31T22:00:00  2004-12-31T23:00:00
isDST        (time)         bool              true true ... true true

Is this possible and what function should be used in xarray, pandas or numpy?



from xarray - apply a function to the time dimension of a DataArray and add the result as a variable

No comments:

Post a Comment