两个形状不同的numpy数组之间的组合

3

我知道使用numpy中的meshgrid函数可以得到两个数组之间所有的组合。

但在我的情况下,我有一个n行两列的数组和另一个数组,我想要获取唯一的组合。

例如:

a = [[1,1],
     [2,2],
     [3,3]]

b = [5,6]

# The expected result would be:

final_array = [[1,1,5],
               [1,1,6],
               [2,2,5],
               [2,2,6],
               [3,3,5],
               [3,3,6]]

仅使用numpy,哪种方法是获得此结果最快的方式?

提出的解决方案

好的,已经得到了结果,但我想知道这是否是完成此任务的可靠且快速的解决方案,如果有人能给我任何建议,我将不胜感激。

a_t = np.tile(a, len(b)).reshape(-1,2)  
b_t = np.tile(b, len(a)).reshape(1,-1) 
final_array = np.hstack((a_t,b_t.T)) 
array([[1, 1, 5],
       [1, 1, 6],
       [2, 2, 5],
       [2, 2, 6],
       [3, 3, 5],
       [3, 3, 6]])

对行索引执行笛卡尔积,然后进行索引和列堆叠。 - cs95
请您详细说明一下吗?几乎得到了正确的解决方案,请查看编辑后的问题。 - kaihami
1个回答

0

有点丑,但这是一种方法:

xx = np.repeat(a, len(b)).reshape(-1, a.shape[1])
yy = np.tile(b, a.shape[0])[:, None]
np.concatenate((xx, yy), axis=1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接