Error: Changing months combination in xarray season for India Region #6012
-
In xarray seasonal grouping includes combination of months : DJF, MAM, JJA, SON, but Indian Mainland seasonal climatology include: JJAS (monsoon), ON (post-monsoon), MAM (pre-monsoon) and DJF (winter). For the same I tried the following way to script:
The dataset (ds) has time dim of shape (216, ) i.e., monthly for 18 years, after slicing [2:-1] to remove the Jan, Feb from the first and Dec from the last year in the datasets, the shape reduce to (213, ).
Looking hopefully for any constructive remark or help from the community. Thanks......... |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 2 replies
-
Quick response: does moving the index outside the selection help?
|
Beta Was this translation helpful? Give feedback.
-
not worked!! |
Beta Was this translation helpful? Give feedback.
-
if you look at the implementation of xarray/xarray/core/accessor_dt.py Lines 15 to 20 in 7a201de Since your groups are not that different, you can take the expression (months // 3) % 4 and change the group for September (9 ):
def indian_mainland_seasons(months):
seasons = np.array(["DJF", "MAM", "JJAS", "ON"])
months = np.asarray(months)
return seasons[np.where(months == 9, 2, (months // 3) % 4)] This assumes In [6]: ds = xr.tutorial.open_dataset("rasm")
...:
...: def indian_mainland_seasons(arr):
...: def compute(months):
...: seasons = np.array(["DJF", "MAM", "JJAS", "ON"])
...: months = np.asarray(months)
...: return seasons[np.where(months == 9, 2, (months // 3) % 4)]
...:
...: return xr.apply_ufunc(
...: compute,
...: arr.dt.month,
...: )
...:
...: indian_mainland_seasons(ds.time)
Out[6]:
<xarray.DataArray 'month' (time: 36)>
array(['JJAS', 'ON', 'ON', 'DJF', 'DJF', 'DJF', 'MAM', 'MAM', 'MAM',
'JJAS', 'JJAS', 'JJAS', 'JJAS', 'ON', 'ON', 'DJF', 'DJF', 'DJF',
'MAM', 'MAM', 'MAM', 'JJAS', 'JJAS', 'JJAS', 'JJAS', 'ON', 'ON',
'DJF', 'DJF', 'DJF', 'MAM', 'MAM', 'MAM', 'JJAS', 'JJAS', 'JJAS'],
dtype='<U4')
Coordinates:
* time (time) object 1980-09-16 12:00:00 ... 1983-08-17 00:00:00 |
Beta Was this translation helpful? Give feedback.
-
Also |
Beta Was this translation helpful? Give feedback.
-
Thanks, it also worked perfectly, in case one by one month is selected. 👍🙌 |
Beta Was this translation helpful? Give feedback.
-
On latest Xarray (>2025.04.0) you can do import xarray as xr
from xarray.groupers import SeasonGrouper
ds = xr.tutorial.open_dataset("air_temperature")
ds.groupby(time=SeasonGrouper(["JJAS", "ON", "MAM", "DJF"])).mean() https://docs.xarray.dev/en/latest/user-guide/time-series.html#handling-seasons |
Beta Was this translation helpful? Give feedback.
if you look at the implementation of
time.season
, it will translate months to season labels here:xarray/xarray/core/accessor_dt.py
Lines 15 to 20 in 7a201de
Since your groups are not that different, you can take the expression
(months // 3) % 4
and change the group for September (9
):