You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将二维NumPy数组重塑为更小形状并填充块内最频繁元素?

在NumPy中按块提取二维数组的众数以缩小形状

你可以通过重塑数组并计算每个块的众数来实现需求,以下是两种可行方案:

示例问题重现

首先还原你的场景,原数组通过取块最大值得到缩小后的数组:

import numpy as np

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

# 原方法:按2x2块取最大值
shape = (2, 2, 2, 2)
max_result = x.reshape(shape).max(-1).max(1)
print(max_result)
# 输出:
# [[3 5]
#  [6 5]]

方案1:使用scipy.stats.mode(简洁高效)

scipy的mode函数可以直接计算指定轴上的众数,适合快速实现需求:

from scipy.stats import mode

# 将数组重塑为(块行数, 块列数, 块元素总数),这里每个2x2块展平为4个元素
x_reshaped = x.reshape(2, 2, -1)
# 对每个块的元素轴(最后一维)计算众数,squeeze去除多余维度
mode_result = mode(x_reshaped, axis=-1)[0].squeeze()
print(mode_result)
# 输出:
# [[1 2]
#  [1 5]]

说明:mode返回的元组中第一个元素是众数值,squeeze()用来把结果从(2,2,1)压缩为(2,2)的目标形状。

方案2:纯NumPy实现(无额外依赖)

如果不想引入scipy,可以用np.unique结合轴操作实现:

# 同样先将数组重塑为(2,2,4)
x_reshaped = x.reshape(2, 2, -1)

# 对每个块统计唯一元素及出现次数
unique_vals, counts = np.apply_along_axis(
    lambda arr: np.unique(arr, return_counts=True),
    axis=-1,
    arr=x_reshaped
)

# 提取每个块中计数最高的元素
mode_result = np.array([
    [vals[np.argmax(cnts)] for vals, cnts in zip(row_unique, row_counts)]
    for row_unique, row_counts in zip(unique_vals, counts)
])
print(mode_result)
# 输出:
# [[1 2]
#  [1 5]]

说明:当块中存在多个元素出现次数相同时,np.argmax会返回第一个出现的最大计数对应的元素;如果需要处理多众数场景,可以根据需求调整逻辑。

内容的提问来源于stack exchange,提问作者D.Vrebos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 10:42:30