Search code examples
pythonmathnumpymatrixsubtraction

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


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. ​


Solution

  • 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]])