[英]xarray - apply a function to the time dimension of a DataArray and add the result as a variable
我有一個 DataArray da
,其中有一個名為FFDI
的變量,它具有三個維度, time
, latitude
和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
我想要實現的是將以下 function 應用於time
維度的每個時間戳,以計算時間戳是否在夏令時期間以及 output 和 Z84E2C64F38F78BA3EAZ5C905AB5A2DA27。
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())
output 將是 numpy 數組或另一個 DataArray 元素; 然后它將作為名為isDST
的附加變量添加到原始 da 中。
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
這可能嗎?應該在 xarray、pandas 或 numpy 中使用什么 function?
您可以只使用簡單的列表推導並將新坐標添加到DataArray
:
import xarray as xr
import pytz
# example data
x = xr.tutorial.load_dataset("air_temperature").air
local_time_tz = pytz.timezone("Australia/Victoria")
is_dst = [bool(local_time_tz.localize(x).dst()) for x in x.time.to_index()]
x = x.assign_coords(is_dst=("time", is_dst))
# result
# Coordinates:
# * lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
# * lon (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
# * time (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00
# is_dst (time) bool True True True True True ... True True True True True
如果x
是xarray.Dataset
而不是xarray.DataArray
你可以簡單地做:
x['is_dst'] = [bool(local_time_tz.localize(x).dst()) for x in x.time.to_index()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.