[英]calculate percentage difference - python
I am calculating the percentage difference between two values in a list. 我正在计算列表中两个值之间的百分比差异。
#cal percentage dff: (val2/val)/100
values = [0.11889, 0.07485, 0.01070, 0.03076, 0.01606]
values = [int(round(i*100)) for i in values]
conversion_values = []
for x in range(1, len(values), 1):
val_1 = values[x-1]
if val_1 == 0.0: #Check if val_1 is 0.
conversion_values.append('-')
else:
val_2 = values[x]
diff = (val_2/val_1)*100
conversion_values.append(diff)
conversion_values
output:
[0, 0, 300, 0]
Desired output: 所需的输出:
[58, 14, 300, 67]
Not sure what I'm doing wrong here? 不知道我在做什么错吗? In Excel this calculation works fine but not here, must be something to do with the decimal points??
在Excel中,此计算工作正常,但在此处不行,必须与小数点有关?
Note - this is not a question about percentage change, that's a different thing altogether. 注意-这不是关于百分比变化的问题,完全是另一回事。
You are loosing precision when performing (val_2)/val_1
so convert either one of them to float to get the end result as floats and then convert the result to int 您在执行
(val_2)/val_1
时失去了精度,因此将其中一个转换为float以获得浮点数的最终结果,然后将结果转换为int
values = [0.11889, 0.07485, 0.01070, 0.03076, 0.01606]
values = [int(round(i*100)) for i in values]
conversion_values = []
for x in range(1, len(values), 1):
val_1 = values[x-1]
if val_1 == 0.0: #Check if val_1 is 0.
conversion_values.append('-')
else:
val_2 = values[x]
diff = int(round((float(val_2)/val_1)*100)) # change to float -->round--> int
conversion_values.append(diff)
conversion_values
Output: 输出:
[58, 14, 300, 67]
Looks like you're using integer division. 看起来您正在使用整数除法。 Please rewrite this
请改写这个
diff = (val_2/val_1)*100
to this 对此
diff = (val_2/float(val_1))*100
or even to this 甚至对此
diff = (val_2/(val_1 * 1.0))*100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.