Skip to content Skip to sidebar Skip to footer

Difference Between Each Elements In An Numpy Array

If I have an array with 4 int [a,b,c,d] and I want a difference between each element to another element, which the result looks like: [a-b, a-c, a-d,b-c,b-d,c-d] The sign does ma

Solution 1:

numpy

At each element, you want to subtract off the elements that come after it. You can get the indices for this using np.trui_indices. The rest is just subtraction:

a, b = np.triu_indices(4, 1)
result = array_1[a] - array_1[b]

The second argument to triu_indices moves you up one diagonal. The default is 0, which includes the indices of the main diagonal:

>>> a
array([0, 0, 0, 1, 1, 2], dtype=int64)
>>> b
array([1, 2, 3, 2, 3, 3], dtype=int64)

>>> array_1[a]
array([1, 1, 1, 2, 2, 3])
>>> array_1[b]
array([2, 3, 4, 3, 4, 4])

>>> result
array([-1, -2, -3, -1, -2, -1])

If you ever need the input sorted by b instead of a, use np.tril_indices:

b, a = np.tril_indices(4, -1)

itertools

You can accomplish the same thing with itertools.combinations:

result = [a - b for a, b in itertools.combinations(array_1, 2)]

Wrap the result in an array if you want.


Solution 2:

This is slightly different, but not as elegant as @Mad-Physicist 's answer. This uses broadcasting to get the differences.

import numpy as np
aa = np.arange(0,4,1);
bb = np.arange(4,8,1);
aa = aa[np.newaxis,:];
bb = bb[:,np.newaxis];
dd = aa - bb;
idx = np.triu_indices(4,1);
print(dd[idx])

Post a Comment for "Difference Between Each Elements In An Numpy Array"