Skip to content

Computing 'seasonal means' spanning 4 months (with resample or groupy) #6180

Answered by mathause
oliviermarti asked this question in Q&A
Discussion options

You must be logged in to vote

You can use xr.dot to 'emulate' groupby (xr.dot only works for DataArrays but it should get you there). xr.dot does the same as (air.air * seasons).sum("time") but more efficient.

import xarray as xr

# load example dataset and create monthly means
air = xr.tutorial.open_dataset("air_temperature")
air = air.resample(time="M").mean()

# find months belonging to season
DJFM = air.time.dt.month.isin([12, 1, 2, 3])
MAMJ = air.time.dt.month.isin([3, 4, 5, 6])

concat_dim = xr.DataArray(["DJFM", "MAMJ"], dims="season")

seasons = xr.concat([DJFM, MAMJ], dim=concat_dim)

# calc mean over seasons
xr.dot(air.air, seasons)

Replies: 3 comments 8 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by andersy005
Comment options

You must be logged in to vote
8 replies
@dcherian
Comment options

@mathause
Comment options

@trexfeathers
Comment options

@trexfeathers
Comment options

@dcherian
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #6087 on January 21, 2022 05:54.