I need to know if I'm time-slicing the xarray data from Jan 1991 through Dec 2021 that I have. 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 -
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. It looks like the data might be in daily form but the download type is 'monthly_averaged_reanalysis' ERA5 data.
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.
For your example, to generate a monthly mean of Dec 2021 you could do:
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):
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.