Reputation: 583
I have a list of values and I want to get difference percentage of the each element with others.
x[1] with x[2],x[3],x[4]
x[2] with x[1],x[3],x[4] and so on.
x =["3150000", "3156000", "3150000","3250000"]
Here is what I want using python:
((3150000 - 3156000) / 3150000) * 100
Desired output:
[-0.19, 0, 3.17, 0.19, 0.19 ..., 3.08]
What's the most efficient way to do this?
Upvotes: 0
Views: 595
Reputation: 9197
You can use itertools.permutations
:
import itertools
def func(l):
return round(((l[0] - l[1]) / l[0]) * 100)
lst = ["3150000", "3156000", "3150000","3250000"]
# map the string values in list to their integer counterpart
lst = map(int, lst)
# create permutations of length 2 from list
permutations = list(itertools.permutations(lst, 2))
# apply function to the permutations
results = {l: func(l) for l in permutations}
# print results
print(*results.items(), sep='\n')
((3150000, 3156000), -0.19)
((3150000, 3150000), 0.0)
((3150000, 3250000), -3.17)
((3156000, 3150000), 0.19)
((3156000, 3250000), -2.98)
((3250000, 3150000), 3.08)
((3250000, 3156000), 2.89)
As one-liner:
results = {l: func(l) for l in list(itertools.permutations(map(int, lst), 2))}
Upvotes: 0
Reputation: 40668
Assuming you are looking for all possible difference pairs.
You can compute the matrix of differences with broadcasting, then divide back and normalize to a percentage:
>>> (x - x[:, None])/x*100
array([[ 0. , 0.19011407, 0. , 3.07692308],
[-0.19047619, 0. , -0.19047619, 2.89230769],
[ 0. , 0.19011407, 0. , 3.07692308],
[-3.17460317, -2.97845374, -3.17460317, 0. ]])
Where component at position i
, j
corresponds to (x[i] - x[j]) / x[i] * 100
.
I did preprocess x
with:
>>> x = np.array([int(i) for i in x])
array([3150000, 3156000, 3150000, 3250000])
Similarly you could use np.array(x).astype(float)
.
Upvotes: 0
Reputation: 1875
is this what you want?
x =["3150000", "3156000", "3150000","3250000"]
x = list(map(int, x))
for x1 in x:
for x2 in x:
if x1 == x2:
continue
diff_per = abs(x1 - x2) / x1 * 100
print("abs({x1} - {x2}) / {x1} * 100 == {:.2f}%".format(diff_per, x1=x1, x2=x2))
output:
abs(3150000 - 3156000) / 3150000 * 100 == 0.19%
abs(3150000 - 3250000) / 3150000 * 100 == 3.17%
abs(3156000 - 3150000) / 3156000 * 100 == 0.19%
abs(3156000 - 3150000) / 3156000 * 100 == 0.19%
abs(3156000 - 3250000) / 3156000 * 100 == 2.98%
abs(3150000 - 3156000) / 3150000 * 100 == 0.19%
abs(3150000 - 3250000) / 3150000 * 100 == 3.17%
abs(3250000 - 3150000) / 3250000 * 100 == 3.08%
abs(3250000 - 3156000) / 3250000 * 100 == 2.89%
abs(3250000 - 3150000) / 3250000 * 100 == 3.08%
Upvotes: 1