用最频繁的元素重塑 2d numpy 数组

问题描述 投票:0回答:1

我想将 2d numpy 数组重塑为更小的形状,并用指定块中最常见的元素填充它。

例如,要从形状 (4,4) 变为 (2,2),我可以使用 reshape 和 max 来获取最大值:

x = numpy. array([[1, 1, 2, 2],
                  [3, 2, 5, 4],
                  [3, 6, 5, 2],
                  [1, 1, 5, 1]])

shape = (2, 2, 2, 2)

x.reshape(shape).max(-1).max(1)

这将给出形状 (2,2),其中 (2,2) 的每个块具有最大值:

[[3 5]
 [6 5]]

但是有没有办法获得一个类似的数组,其中每个 4 块的出现次数最多的值? 结果应该是:

[[1 2]
 [1 5]]
python arrays numpy reshape
1个回答
0
投票

您可以使用列表理解来获取所需的所有块

x = [[1, 1, 2, 2],
     [3, 2, 5, 4],
     [3, 6, 5, 2],
     [1, 1, 5, 1]]

top_left = [a[:2] for a in x[:2]]
#[[1, 1], [3, 2]]

top_right = [a[2:] for a in x[:2]]
#[[2, 2], [5, 4]]

bottom_left = [a[:2] for a in x[2:4]]
#[[3, 6], [1, 1]]

bottom_right = [a[2:] for a in x[2:4]]
#[[5, 2], [5, 1]]

压平这些块并获得众数:

from statistics import mode

mode([item for sublist in top_left for item in sublist])
#1

mode([item for sublist in top_right for item in sublist])
#2

mode([item for sublist in bottom_left for item in sublist])
#1

mode([item for sublist in bottom_right for item in sublist])
#5
© www.soinside.com 2019 - 2024. All rights reserved.