简体   繁体   中英

Finding highest values of xarray DataArray along the third dimension.

I have a 3 dimensional xarray DataArray, where two dimensions represent a xy grid and the third one the number of grid-layers "stacked" on each other. The empty DataArray looks like this:

import xarray as xr
import numpy as np

data = np.zeros(shape=(layers,y,x))
dims=['layer','y_Axis', 'x_Axsis']
dataArray = xr.DataArray(data,dims=dims)

Within a routine I am filling up the grids layer by layer with values between -1 and 1.

My task now is to stack all layers together into one selecting to highest values of all grids combined. So when for instance 5 layers are compared with each other the highest elements within the grid will be saved in a 2d numpy array.

I could solve this by looping through every layer comparing the grid values of the current layer with a created 2d max_val_grid and thus filtering through the third dimension. However this sounds very inefficient.

Has anyone of you an idea how to solve this using internal xarray or numpy functions without looping?

thanks alot!

You can use numpy.amax as follows

numpy.amax(your_3D_array, axis=2)

This will select the maximum values of your_3D_array on the last axis of the 3D data and return a 2D array. Here is a quick test case:

import numpy as np

x = np.arange(10)
y = np.arange(10, 20)
z = np.arange(20, 30)

x, y, z = np.meshgrid(x, y, z)

print(np.amax(z, axis=2))

xarray 中的max()方法完全符合您的要求,例如dataArray.max('layer')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM