如何对两个二维NumPy数组进行逐元素Zip配对?
将两个二维NumPy数组逐元素配对为元组数组的解决方法
给定两个形状完全相同的二维NumPy数组:
import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) b = np.array([[1,2,3],[4,5,6],[7,8,9]])
目标是得到逐元素配对后的结果:
[[(1,1) (2,2) (3,3)] [(4,4) (5,5) (6,6)] [(7,7) (8,8) (9,9)]]
原代码错误分析
你尝试的代码:
np.array(list(zip(np.ndarray.flatten(a),np.ndarray.flatten(b)))).reshape(a.shape)
报错cannot reshape array of size 18 into shape (3,3),原因是:
NumPy默认会把zip生成的元组拆分为独立数值,生成形状为(9,2)的数组(总元素数18),而reshape(3,3)需要9个元素,因此无法匹配。
解决方案
方案1:指定dtype=object保留元组
修改原代码,通过dtype=object让NumPy将每个元组视为单个元素:
result = np.array(list(zip(a.flatten(), b.flatten())), dtype=object).reshape(a.shape) print(result)
输出:
[[(1, 1) (2, 2) (3, 3)] [(4, 4) (5, 5) (6, 6)] [(7, 7) (8, 8) (9, 9)]]
方案2:列表推导式直接索引配对
无需展平数组,按行列索引直接配对元素:
result = np.array([[(a[i,j], b[i,j]) for j in range(a.shape[1])] for i in range(a.shape[0])], dtype=object) print(result)
方案3:利用np.stack+apply_along_axis转换
先将两个数组在最后一维堆叠,再将每个子数组转为元组:
stacked = np.stack((a, b), axis=-1) result = np.apply_along_axis(tuple, 2, stacked) print(result)
np.stack生成形状为(3,3,2)的数组,apply_along_axis沿最后一维将每个长度为2的子数组转为元组,最终得到目标结构。
内容的提问来源于stack exchange,提问作者Pixel_Bear
相关产品推荐
相关产品推荐

