Xarray find maximum value for each grid point across time

Viewed 191

I have the following netcdf file, which contains daily rainfall (precip) over a region, and I have opened it as an xarray.

<xarray.Dataset>
Dimensions:    (latitude: 500, longitude: 600, time: 120)
Coordinates:
  * latitude   (latitude) float32 -35.22 -35.17 -35.12 ... -10.38 -10.33 -10.28
  * longitude  (longitude) float32 10.27 10.32 10.38 10.43 ... 40.12 40.18 40.22
  * time       (time) datetime64[ns] 2022-01-01 2022-01-02 ... 2022-04-30
Data variables:
    precip     (time, latitude, longitude) float32 ...
Attributes: (12/15)
    Conventions:       CF-1.6
    title:             CHIRPS Version 2.0
    history:           created by Climate Hazards Group
    version:           Version 2.0
    date_created:      2022-05-16
    creator_name:      Pete Peterson
    ...                ...
    reference:         Funk, C.C., Peterson, P.J., Landsfeld, M.F., Pedreros,...
    comments:           time variable denotes the first day of the given day....
    acknowledgements:  The Climate Hazards Group InfraRed Precipitation with ...
    ftp_url:           ftp://chg-ftpout.geog.ucsb.edu/pub/org/chg/products/CH...
    website:           http://chg.geog.ucsb.edu/data/chirps/index.html
    faq:               http://chg-wiki.geog.ucsb.edu/wiki/CHIRPS_FAQ

I would like to pull out the maximum precip value at each grid point (i.e. each lat/lon point). I need the maximum value to keep its attributes of latitude, longitude and time because I will then analyse when and where these maximums occurred.

I know I can use the following to get a maximum value at the first grid point, across time. But how do I then see where this max occurs and on what date?

ds1a.precip[:,0,0].max()

I am really struggling to then do this for all grid points. I would really appreciate guidance.

1 Answers

In general

Both methods have the optional parameter dim, to specify which dimension to find the maximum over.

In your case,

ds1a.max(dim='time')

will return a dataset with the maximum over time per each latitude and longitude, and

ds1a.argmax(dim='time')

will return the time at which this maximum is attained.

Here's a reproducible example with sample data:

import xarray as xr

ds = xr.tutorial.open_dataset('air_temperature').load()
ds.max(dim='time')
ds.argmax(dim='time')
Related