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

如何不使用循环对numpy数组的块进行列合并重组?

高效实现Numpy数组块列拼接

给定输入数组:

import numpy as np

arr = np.array([[0., 0., 0., 0.],
                [0., 0., 0., 0.],
                [1., 1., 1., 1.],
                [1., 1., 1., 1.],
                [2., 2., 2., 2.],
                [2., 2., 2., 2.],
                [3., 3., 3., 3.],
                [3., 3., 3., 3.]])

可以用Numpy的向量化操作替代循环,高效完成需求,步骤如下:

方法一:重塑维度+批量拼接

通过重塑数组维度拆分块,再批量配对拼接:

# 将数组重塑为(块数, 块内行数, 块内列数)的三维结构
blocks = arr.reshape(4, 2, 4)
# 配对偶数索引块与奇数索引块,按列拼接后展平为目标形状
result = np.concatenate([blocks[::2], blocks[1::2]], axis=2).reshape(-1, 8)

方法二:切片直观拼接

通过切片拆分区域,逐个拼接后合并:

# 拆分前两个块、后两个块的区域
upper_section = arr[:4]
lower_section = arr[4:]
# 每两个行块按列拼接
upper_combined = np.hstack([upper_section[::2], upper_section[1::2]])
lower_combined = np.hstack([lower_section[::2], lower_section[1::2]])
# 合并两部分结果
result = np.vstack([upper_combined, lower_combined])

验证结果

运行后得到的result即为目标数组:

array([[0., 0., 0., 0., 1., 1., 1., 1.],
       [0., 0., 0., 0., 1., 1., 1., 1.],
       [2., 2., 2., 2., 3., 3., 3., 3.],
       [2., 2., 2., 2., 3., 3., 3., 3.]])

以上两种方式均采用Numpy原生向量化操作,完全避免循环依赖,利用底层优化实现高效计算,数组规模越大,性能优势越明显。

内容的提问来源于stack exchange,提问作者dmn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:33:22