我知道可以使用 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/