在保持形状不变的情况下,将2个2D numpy数组元素组合成相同的形状

时间:2020-08-23 08:36:56

标签: python python-3.x numpy numpy-ndarray

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

#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)]])

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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)]]

答案 1 :(得分:1)

按如下方式使用dstack :(其中xy是您的第一和第二个数组)

np.dstack((x,y))