11

I have an xarray DataArray that I want to select the months April, May, June (similar to time.season=='JJA') for an entire time series.

Its structured like:

<xarray.DataArray 't2m' (time: 492, latitude: 81, longitude: 141)>

I have been previously selecting JJA by:

seasonal_data =temp_data.sel(time=temp_data['time.season']=='JJA')

I would like to do the same thing but with the months 'AMJ' instead. I can add any details that I might be missing.

Thanks

2 Answers 2

29

The easiest way to select custom months is to use boolean masks, e.g.,

def is_amj(month):
    return (month >= 4) & (month <= 6)

seasonal_data = temp_data.sel(time=is_amj(temp_data['time.month']))

Note that you need to use the bitwise operators like & or | because Python's built-ins and and or don't work on vectors. Also, you need the parentheses because bitwise operators have higher precedence than comparisons.

Sign up to request clarification or add additional context in comments.

4 Comments

I had been trying to do this, but kept getting errors. This method worked super well. I assume that is how the time.season=='JJA' works in the underlying code?
Take a look for yourself: github.com/pydata/xarray/blob/… We actually use a trick with integer division modulo 4, which is probably slightly faster but also less clear (and less generalizable).
Hi @shoyer, Thanks for the example above. Its helped a lot. Additionally, I was wondering how do one can select, lets say, the Dec month from the previous year and a few months from the current year together. I tried the below function, but that gives an an empty array. (def is_djfma(month): return (month >= 12) & (month <= 4)) Do you have any quick suggestion for this? Thanks, Arindan.
@ArindanMandal wrapped months are easier to handle with the isin method.
2

Another way to do this is using the isin method:

# April, May and June:
data=temp_data.sel(time=temp_data.time.dt.month.isin([4,5,6]))

This makes handling "wrapped" seasons (e.g. DJFM) so much easier, in response to some of the comments under the accepted answer, e.g.:

# DJFM
data=temp_data.sel(time=temp_data.time.dt.month.isin([1,2,3,12]))

This is the recommended way to select months in the xarray documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.