问题
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 matter, I try shift the array, but there should be a better way to do this, Cause this seems like some math problem that I forgot.
import numpy as np
array_1 = np.array([1,2,3,4])
array_2 = np.copy(array_1)
array_2 = np.roll(array_2,-1)
array_2[-1] = 0
array_3 = np.copy(array_2)
array_3 = np.roll(array_3,-1)
array_3[-1] = 0
result_1n2 = array_1-array_2
result_1n3 = array_1-array_3
result_last = array_1[0] - array_1[-1]
array_result = [result_1n2[0],result_1n3[0], result_last, result_1n2[1], result_1n3[1], result_1n2[2]]
print(array_result)
[-1, -2, -3, -1, -2, -1]
How should I approach this?
回答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.
回答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])
来源:https://stackoverflow.com/questions/64071016/difference-between-each-elements-in-an-numpy-array