Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select xarray/pandas index based on specific months

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

like image 251
Gabe Avatar asked Oct 26 '16 21:10

Gabe


People also ask

How do I access Xarray data?

xarray offers extremely flexible indexing routines that combine the best features of NumPy and pandas for data selection. The most basic way to access elements of a DataArray object is to use Python's [] syntax, such as array[i, j] , where i and j are both integers.

How do I drop a dimension in Xarray?

In future versions of xarray (v0. 9 and later), you will be able to drop coordinates when indexing by writing drop=True , e.g., ds['bar']. sel(x=1, drop=True) .

What is Python Xarray?

xarray (formerly xray) is an open source project and Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!


1 Answers

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.

like image 92
shoyer Avatar answered Sep 18 '22 19:09

shoyer