快速处理二维数组的方法是按第二个二维数组中的值分组吗?

2024-05-15 12:54:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我正在尝试理解如何处理这些数组而不以迭代的方式遍历它们,事实证明这太慢了

我有两个数组,它们都是相同的形状(480,640),称为“heights”和sectors你可以想象我有一个480x640的麦穗图,每个麦穗都有一个给定的高度,图被分成“扇区”

假设我要计算每个区段的小麦平均高度,并将每个麦头的高度与各自区段的小麦平均高度进行比较。我可以用for循环迭代地实现这一点,但我正在寻找一种更快的方法

“heights”是一组浮点数,如下所示:

[[1.343  2.456  2.345...  3.123  1.456  2.765]
 [2.445  3.556  3.778 ... 3 667  2.112  2 752]
 [2.567  3.567  1.334...  3.778  1.228  3.550]
...
 [3.112  1.001  1.332...  2.334  2.445  1 220]
 [2.754  1.457  1.754...  1.786  2.789  3.991]
 [1.003  2.009  2.354...  1.112  3.449  3.993]]  

“扇区”是一个整数数组,看起来像这样(整个阵列最多有20个扇区,有点像日本国旗,每个太阳光线都有自己的编号,太阳和周围的边界也是如此,但扇区的排列对问题并不重要)

[[0. 0. 0. ... 0. 0. 0.]
 [0. 2. 2. ... 2. 2. 0.]
 [0. 2. 1. ... 1. 2. 0.]
 ...
 [0. 3. 1. ... 1. 2. 0.]
 [0. 3. 3. ... 2. 2. 0.]
 [0. 3. 3. ... 4. 4. 0.]]

所以现在如果我把两个数组叠加起来,每个麦穗都会根据它在数组中的位置与它自己的扇区号相关联。每个部门可能有大约4000到9000头小麦

我想做的是尽可能快地找到每个扇区内所有高度的平均值

随后,我想将“heights”中的每个值与其各自的扇区值进行比较

最后,我想使用比较来创建一个新数组(在下面的示例中,我创建了一个黑白图像掩码,但这对问题并不重要)

我尝试用for循环进行迭代,如下所示:

def enumerate2D(array1, array2):
    assert array1.shape == array2.shape, "Error - dimensions."
    for indexes, data in np.ndenumerate(array1):
        yield indexes, data, array2[indexes]


#create container to eventually hold averages for each sector
comparebins = np.zeros(numberofSectors)

#container for tallying how many pixels lie in each sector
inEach = np.zeros(numberofSectors,int)          

# find sum of heights in each sector
for index, sector, height in enumerate2D(sectors, heights):
    comparebins[sector] = comparebins[sector] + height
    inEach[sector] += 1

#average each sector 
comparebins  = comparebins / inEach  


# Now that I have the averages, I have to run through heights again,
# applying a conditional and using indices to write each pixel of a mask

#create an image mask
maskoid = np.zeros((480, 640))

#now check each height value again
for index, sector, height in enumerate2D(sectors, heights): 
    if abs(height - comparebins[sector]) > someThreshold:
        maskoid2[index] = 255

这种方法可行,但耗时太长。我在做视频,所以我需要每秒能做30次。为了提高速度,我可以将数组缩小到当前大小的30%,但是使用这种迭代方法,使用25%大小的数组仍然需要很长时间

似乎我应该能够使用某种快速的“矢量化”熊猫或numpy操作。我试着用熊猫和groupby

但是我一辈子都搞不懂如何使用我的两个数组创建DataFrame对象。我走对了吗?这看起来应该更容易,但我不习惯python数组,尤其是索引、切片、轴等等


Tags: 方法infor高度np数组eachheight