pythongroup-bypython-xarray

How to select DJFM season instead of xarray groupby


I am relatively new to python and programming and have been trying to make some initial plots of precipitation data for the Indian subcontinent specifically for the indian winter monsoon through the period of December, January, February, March.

I have noticed that in groupby('time.season').mean(dim='time') only work for DJF

is there a way to get 4 month (DJFM) seasonal average?


Solution

  • If you want the average for a specific set of months over the whole dataset, you can select the months using the time accessor dt and isin, then apply mean. So in your case:

    da[da.time.dt.month.isin([12,1,2,3])].mean(dim = 'time')
    

    If you want the average over a set of 4 months for each year, you can first resample your data to a monthly time step, then calculate the rolling mean over 4 time steps and select the period you want. So in your case:

    #Resampling
    da_ = da.resample(time = '1M').mean()
    
    #Rolling mean
    da_ = da_.rolling(time = 4).mean()
    
    #Select March to get the average over DJFM
    da_[da_.time.dt.month == 3]