选择具有最高均值的数组

Picking the array with the highest mean

使用 xarray,我可以定义一个 3D 数组:

>>> array = xr.DataArray(
[[[3, 2, 1], [3, 1, 2], [2, 1, 3]], [[1, 3, 2], [2, 5, 1], [2, 3, 1]]],
dims=("x", "y", "z"))

>>> array
<xarray.DataArray (x: 2, y: 3, z: 3)>
    array([[[3, 2, 1],
            [3, 1, 2],
            [2, 1, 3]],
           [[1, 3, 2],
            [2, 5, 1],
            [2, 3, 1]]])
    Dimensions without coordinates: x, y, z

从这个 3D 数组中,我想选择均值最高的 2D 数组层。

我试过这个:

max_layer = array.max(dim='x')

这不起作用。 Python 创建一个沿 x 轴具有最高值的新二维数组,而不是按照我的意愿进行。

>>> max_layer
<xarray.DataArray (y: 3, z: 3)>
    array([[3, 3, 2],
           [3, 5, 2],
           [2, 3, 3]])
    Dimensions without coordinates: y, z

我该如何解决这个问题?

max 属性不会自动计算均值。您必须先取 2D 层的平均值,然后使用 argmax 获取具有最大平均值的 2D 层的索引。

import xarray as xr

array = xr.DataArray(
[[[3, 2, 1], [3, 1, 2], [2, 1, 3]], [[1, 3, 2], [2, 5, 1], [2, 3, 1]]],
dims=("x", "y", "z"))

# Get the means of the 2D layers from the `x` dimension
array_means = array.mean(dim = ['y', 'z'])

# Check the means
print(array_means)

<xarray.DataArray (x: 2)>
array([2.        , 2.22222222])

# Find the index of the 2D layer with the maximum mean
idx = array_means.argmax()

print(array[idx])

<xarray.DataArray (y: 3, z: 3)>
array([[1, 3, 2],
       [2, 5, 1],
       [2, 3, 1]])
Dimensions without coordinates: y, z