简体   繁体   中英

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??

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM