Subtract all pairs of values from two arrays

你。 提交于 2019-12-01 09:21:41

You're not going to have very much fun with the giant arrays that you mentioned. But if you have more reasonably-sized matrices (small enough that the result can fit in memory), the best way to do this is with broadcasting.

import numpy as np

a = np.array(range(5, 10))
b = np.array(range(2, 6))

res = a[np.newaxis, :] - b[:, np.newaxis]
print(res)
# [[3 4 5 6 7]
#  [2 3 4 5 6]
#  [1 2 3 4 5]
#  [0 1 2 3 4]]

np.subtract.outer

You can use np.ufunc.outer with np.subtract and then transpose:

a = np.array(range(5, 10))
b = np.array(range(2, 6))

res1 = np.subtract.outer(a, b).T
res2 = a[np.newaxis, :] - b[:, np.newaxis]

assert np.array_equal(res1, res2)

Performance is comparable between the two methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!