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

I am looking for the fastest method for subtracting all elements of array A from all elements of array B. The only way I know how to do this:

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 get a matrix newthat is quality for[0,1,2;-1,0,1;-2,-1,0]

I would also like to extend this type of operation to the 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 in the end:

[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 it is very slow for very large arrays.

+4
source share
1 answer

Extend bin the case of a 2D array with np.newaxis/None, and then broadcastingplay a role for a quick vectorized solution, for example:

a - b[:,None]

-

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]])
+3

Source: https://habr.com/ru/post/1623984/


All Articles