Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

xarray: How to get the coordinates of the maximum and minimum value over a spatial domain in xarray? #3160

Closed
anubhavchoudhary opened this issue Jul 24, 2019 · 2 comments

Comments

@anubhavchoudhary
Copy link

anubhavchoudhary commented Jul 24, 2019

I have a netcdf file containing a surface variable over a latlon area. I want to get the coordinate (as lat, lon value) of maximum as well as minimum value of that variable over a certain area which I can define with latlon box. How to do it in xarray ?

@TomNicholas
Copy link
Member

There might be a better way, but I think this is one way:

First mask out all the data that isn't in your lat/long box. If your latitude and longitude are 1D then you could use .sel(), otherwise use .where(). You have two conditions (one for latitude and one for longitude), so combine them with np.logical_and():

condition = np.logical_and(data.lat > 10.0, data.lon < 50.0)
box = data.where(condition)

Then use DataArray.argmax() across all the dimensions of the result to find the indices of the maximum values.

inds_of_max = box.argmax(dims=['lat', 'lon'])

Pass those indices to your latitude/longitude coordinate arrays to get the (lat, lon) pair you want.

lat, lon = data.lat[inds_of_max], data.lon[inds_of_max]

(This would probably be better placed on stackoverflow than here but doesn't matter)

@shoyer
Copy link
Member

shoyer commented Jul 25, 2019

In fact, this was already asked on StackOverflow :)
https://stackoverflow.com/questions/40179593/how-to-get-the-coordinates-of-the-maximum-in-xarray

I'm going to close this, but feel free to comment or reopen if you have any further questions.

@shoyer shoyer closed this as completed Jul 25, 2019
@pydata pydata locked and limited conversation to collaborators Aug 1, 2023
@andersy005 andersy005 converted this issue into discussion #8036 Aug 1, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Projects
None yet
Development

No branches or pull requests

3 participants