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

标签 python arrays numpy

我知道可以使用 meshgrid 来使用 numpy 获取两个数组之间的所有组合。

但就我而言,我有一个由两列和 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]])

最佳答案

有点难看,但这是一种方法:

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)

关于python - numpy不同形状的两个数组之间的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276732/

相关文章:

c - 将 PyArrayObject 传递给 C 函数

python - numpy.einsum 的输出形状

python - zc.buildout 停止工作 : ImportError: No module named apport. fileutils

c# - LINQ 列表属性到数组?

arrays - 如何在 Rails 4.2 表单中提交字符串数组

javascript - PHP (AJAX) 的对象数组

python - 将 numpy 数组保存到 txt

python - Gmail API Python : RequestTooLargeError: The request to API call datastore_v3. Put() 太大

python - 如何向 NumPy 中的矩阵添加保护环?

python - Elasticsearch:我想计算特定值在特定字段中出现的次数