首页 > 解决方案 > 如何找到具有相同长度的多个数组的最小值的数组

问题描述

我有一个维度为 (29,320,180) 的多维网格数组,其中 29 是数组的数量,320 是纬度值,180 是经度值。我想在所有 29 个数组中找到每个网格点的最小值,所以最后我可以有一个尺寸为 320x180 的数组,由每个网格点的最小值组成。我必须破坏每个数组都有大量的 nan 值。我怎样才能做到这一点?例如两个具有相同维度的数组: a=[[1,2,3],[3,5,8],[4,8,12]] b=[[3,5,6],[9,12 ,5],[5,6,14]] 并且想要的输出将是一个数组,每个索引处都有最小值,意思是:c=[[1,2,3],[3,5,5],[ 4,6,12]]

标签: pythonarraysmin

解决方案


我不确定您是否需要每个数组的列或行的最小值,您可以通过下面的示例选择您想要的。

让我们创建几个小型二维数组的示例:

import numpy as np
ex_dict = {}
lat_min = []
lon_min = []
# creating fake data assuming instead of the 29 arrays of dimensions 320x180 you have 5 arrays of dimensions 2x5 (so we can see the output) and all the arrays are stored in a dictionnary (because it's easier for me to randomly create them that way :)
for i in range(0,5):
    ex_dict[i] = np.stack([np.random.choice(range(i,20), 5, replace=False) for _ in range(2)])

让我们看看我们的数组:

ex_dict
{0: array([[19, 18,  5, 13,  6],
        [ 5, 12,  3,  8,  0]]),
 1: array([[10, 13,  2, 19, 15],
        [ 5, 19,  6,  8, 14]]),
 2: array([[ 5, 17, 10, 11,  7],
        [19,  2, 11,  5,  6]]),
 3: array([[14,  3, 17,  4, 11],
        [18, 10,  8,  3,  7]]),
 4: array([[15,  8, 18, 14, 10],
        [ 5, 19, 12, 16, 13]])}

然后让我们创建一个列表来存储每个数组的最小值(lat_min 包含所有数组中每个 raw 和 lat_lon 的最小值):

# for each of the 5 arrays (in this example, stored in the ex_dict dictionnary), find the minimum in each row (axis = 1) and each column (axis = 2)
for i in ex_dict:
    lat_min.append(np.nanmin(ex_dict[i], axis=1))
    lon_min.append(np.nanmin(ex_dict[i], axis=0)) 

我们的最小值列表:

lat_min
[array([5, 0]), array([2, 5]), array([5, 2]), array([3, 3]), array([8, 5])]

lon_min
[array([ 5, 12,  3,  8,  0]),
 array([ 5, 13,  2,  8, 14]),
 array([ 5,  2, 10,  5,  6]),
 array([14,  3,  8,  3,  7]),
 array([ 5,  8, 12, 14, 10])]

推荐阅读