[英]Time Slice Python Xarray Dataarray
I need to know if I'm time-slicing the xarray data from Jan 1991 through Dec 2021 that I have.我需要知道我是否对我拥有的 1991 年 1 月至 2021 年 12 月的 xarray 数据进行时间切片。 The coordinates look like this:
坐标如下所示:
Coordinates:
* time (time) datetime64[ns] 1991-01-31 1991-02-28 ... 2021-12-31
number int32 0
step timedelta64[ns] 00:00:00
surface float64 0.0
* latitude (latitude) float64 58.0 57.75 57.5 57.25 ... 23.5 23.25 23.0
* longitude (longitude) float64 -130.0 -129.8 -129.5 ... -63.5 -63.25 -63.0
The line of code that I'm using to slice through the dataarray (resultm) looks like this -我用来切片数据数组(resultm)的代码行如下所示 -
month_curr = resultm.sel(time=slice('2021-12','2021-12')).groupby('time.month').mean(dim='time')
And, my objective is to slice or extract all the December 2021 data - which should be a monthly value.而且,我的目标是分割或提取所有 2021 年 12 月的数据——这应该是月度值。 It looks like the data might be in daily form but the download type is 'monthly_averaged_reanalysis' ERA5 data.
看起来数据可能是每日形式,但下载类型是“monthly_averaged_reanalysis”ERA5 数据。
Thank you,谢谢,
You can select the relevant data using the datetime accessor .dt
where you need to combine both dt.month
and dt.year
using numpy.logical_and
to generate a boolean index which corresponds to the required indices.您可以使用日期时间访问器
.dt
select 相关数据,其中您需要使用numpy.logical_and
组合dt.month
和dt.year
并生成对应于所需索引的 Z84E2C64F38F28BA3EA5C905AB5 索引。
For your example, to generate a monthly mean of Dec 2021 you could do:对于您的示例,要生成 2021 年 12 月的月平均值,您可以执行以下操作:
import numpy as np
month_curr = resultm.sel(
time=np.logical_and(
resultm.time.dt.year == 2021, resultm.time.dt.month == 12
)
)
month_curr = month_curr.mean("time")
Here's a toy example (using the year 2013):这是一个玩具示例(使用 2013 年):
import xarray as xr
import numpy as np
x = xr.tutorial.load_dataset("air_temperature")
xs = x.sel(
time=np.logical_and(x.time.dt.month == 12, x.time.dt.year == 2013)).mean("time")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.