Subracting all elements of array A from all elements of B?

旧城冷巷雨未停 提交于 2019-12-01 20:10:38

问题


I am looking for the quickest method to subtract all elements of array A, from all elements of array B. The only way I know how to do it is:

a = np.array([1,2,3])
b = np.array([1,2,3])
new = []
for i in a:
    new.append(b - a[i])

Ideally, I would like to end up with a matrix new which would be qual to [0,1,2;-1,0,1;-2,-1,0]

I would also like to extend this type of operation to Pandas timedelta series. For example, I can do this:

a=np.array([1,2,3])
b=np.array([1,2,3])
aT = pd.to_timedelta(a,'D')
bT = pd.to_timedelta(b,'D')
new = []

for i in aT:
    x.append(bT - i)

and end up with this:

[TimedeltaIndex(['0 days', '1 days', '2 days'], dtype='timedelta64[ns]', freq='D'), TimedeltaIndex(['-1 days', '0 days', '1 days'], dtype='timedelta64[ns]', freq='D'), TimedeltaIndex(['-2 days', '-1 days', '0 days'], dtype='timedelta64[ns]', freq='D')]

but that's very slow for very large arrays. ​


回答1:


Extend b to a 2D array case with np.newaxis/None and then let broadcasting play its part for a fast vectorized solution, like so -

a - b[:,None]

Sample run -

In [19]: a
Out[19]: array([1, 2, 3])

In [20]: b
Out[20]: array([1, 2, 3])

In [21]: a - b[:,None]
Out[21]: 
array([[ 0,  1,  2],
       [-1,  0,  1],
       [-2, -1,  0]])


来源:https://stackoverflow.com/questions/34752124/subracting-all-elements-of-array-a-from-all-elements-of-b

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