Select to view content in your preferred language

Python - Negative value with field Calculator

7266
13
Jump to solution
07-24-2012 05:47 AM
Pierre-LucBoivin
Frequent Contributor
Hi,

I'm trying to subtract two integer columns and put the result into a text field. I got good result with positive valuesâ??â??, but I have a problem with negative valuesâ??â??.

[ATTACH=CONFIG]16352[/ATTACH]

Variation column is the result I get with this formula :

def Resultat(x,y):
 diff =  x-y
 return '%d:%02d' % divmod(diff, 60)

Variation = Resultat( !ScePUPbr! , !SitPUPbr!)


Testvari column is the result if I reverse the values â??â??xy

Testvari2 column is the result I should get

Thanks you for help

Pierre-Luc
Tags (2)
0 Kudos
13 Replies
Pierre-LucBoivin
Frequent Contributor
Well still doesn't work ! I'm gonna populate my field testvari2 with an selection and concatenation of the column Variation and testVari !!!

For sure, this is not an optimal solution but it'll work.

!Variation![0:1] + !testvari!


Thanks for your help
0 Kudos
ChristopherThompson
Frequent Contributor
I guess I am not understanding the value you are trying to obtain - subtracting a smaller number from a larger number will always return a positive value, and it stands to reason that nearly any action taken using that value will also return another positive value. Absolute value doesn't work because by definition absolute value returns a positive value, it doesn't simply reverse the sign.   Now, if the minus sign is simply symbolic of the the difference between the two numbers, then thats somewhat different though misleading.  What was the expression you put into the field calculator to obtain the negative value?  If you're set on getting a negative value there then this will do it i think:
'-%d:%02d' % divmod(4, 60)
0 Kudos
Pierre-LucBoivin
Frequent Contributor
I absolutely need the negative value because i'm calculating difference between 2 streets network for Emergency travel time. So I need to know the variation(negative or positive) between the different network.
0 Kudos
Pierre-LucBoivin
Frequent Contributor
Here the final solution !

def Resultat(x,y):
 diff =  x-y
 if diff < 0:
  sign = '-'
 else:
  sign = ''
 return sign+'%d:%02d' % divmod(abs(diff), 60)


Thanks everyone for your help
0 Kudos