首页 > 解决方案 > 按元素组合 2 个 2D numpy 数组,形状相同,同时保留它们的形状

问题描述

组合第一个数组和第二个数组中的每个元素并创建一个新数组,同时保持相同的形状。

#Numpy Array 1 -- shape 7 X 5 
#X coordinates
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
#Numpy Array 2 -- shape 7 X 5
#Y coordinates
 array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6]])

所需的输出应该是一个元组数组。

#Desired Output -- shape 7 X 5
#(X,Y) combination
array([[(0,0), (1,0), (2,0), (3,0), (4,0)],
       [(0,1), (1,1), (2,1), (3,1), (4,1)],
       [(0,2), (1,2), (2,2), (3,2), (4,2)],
       [(0,3), (1,3), (2,3), (3,3), (4,3)],
       [(0,4), (1,4), (2,4), (3,4), (4,4)],
       [(0,5), (1,5), (2,5), (3,5), (4,5)],
       [(0,6), (1,6), (2,6), (3,6), (4,6)]])

标签: pythonpython-3.xnumpynumpy-ndarray

解决方案


您可以执行以下操作:

import numpy as np

arr1 = np.array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
#Numpy Array 2 -- shape 7 X 5
#Y coordinates
arr2 = np.array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6]])

comb = np.vstack(([arr1.T], [arr2.T])).T
print(comb)

虽然它不是元组数组,但给出几乎相同的结果。

您可以在之后添加步骤以通过以下方式获取元组数组:

import numpy as np

arr1 = np.array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
#Numpy Array 2 -- shape 7 X 5
#Y coordinates
arr2 = np.array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6]])

comb = np.vstack(([arr1.T], [arr2.T])).T

f = np.vectorize(lambda x:tuple(*x.items()), otypes=[np.ndarray])
res = np.apply_along_axis(lambda x:dict([tuple(x)]), 2, comb)
mat2 = np.vstack(f(res))

这将给出以下内容:

[[(0, 0) (1, 0) (2, 0) (3, 0) (4, 0)]
 [(0, 1) (1, 1) (2, 1) (3, 1) (4, 1)]
 [(0, 2) (1, 2) (2, 2) (3, 2) (4, 2)]
 [(0, 3) (1, 3) (2, 3) (3, 3) (4, 3)]
 [(0, 4) (1, 4) (2, 4) (3, 4) (4, 4)]
 [(0, 5) (1, 5) (2, 5) (3, 5) (4, 5)]
 [(0, 6) (1, 6) (2, 6) (3, 6) (4, 6)]]

推荐阅读