Select to view content in your preferred language

Need some Python code for field calculator!

3381
6
Jump to solution
12-02-2013 04:16 AM
by Anonymous User
Not applicable
Original User: jofuchs

Hi all!

I am a very beginner with Python, so that will be an easy task for most of you. 🙂

I want to calculate a new field of an attribute table, something like that: ((Field X/ Field Y)*100). Since 0-Values are existent, I have to exclude these values from dividing.
What I tried so far is displayed in the screenshot, but doesnt word untill now... (Perhaps it is totally wrong...)

[ATTACH=CONFIG]29480[/ATTACH]

I hope you can help me! Many Thanks in advance!

Jo
0 Kudos
1 Solution

Accepted Solutions
AnthonyGiles
Honored Contributor
I have created a sample feature class with three columns a,b and c. A and B are Long and C is a double. The code in the attached screenshot works fine:

[ATTACH=CONFIG]29490[/ATTACH]

Try changing your square brakets in your expression to normal brackets ()

Regards

Anthony

View solution in original post

0 Kudos
6 Replies
by Anonymous User
Not applicable
Original User: ad_giles@hotmail.com

Jo,

Try this:

def calc(f1,f2):
  if (f1 <> 0):
    return (f1/f2)*100
  else:
    return 0


Regards

Anthony
0 Kudos
by Anonymous User
Not applicable
Original User: jofuchs

Hi Anthony,

thanks for your reply. There is still this error message appearing

[ATTACH=CONFIG]29484[/ATTACH]

For your information:
The field i am calculating is double formatted; f1 and f2 are long integer. But I think thsi should be ok so!?

Jo
0 Kudos
AnthonyGiles
Honored Contributor
Jo

It looks like you have zeros for both columns, try

def calc(f1,f2):
  if (f1 <> 0 and f2 <> 0):
    return (f1/f2)*100
  else:
    return 0
0 Kudos
by Anonymous User
Not applicable
Original User: jofuchs

I corrected this, you are right. That might be another potential error, but nevertheless I always have the same error message posted before...

EDIT: Field f1 is long, field f2 is double, target field is double! Can this be a problem?
0 Kudos
AnthonyGiles
Honored Contributor
I have created a sample feature class with three columns a,b and c. A and B are Long and C is a double. The code in the attached screenshot works fine:

[ATTACH=CONFIG]29490[/ATTACH]

Try changing your square brakets in your expression to normal brackets ()

Regards

Anthony
0 Kudos
by Anonymous User
Not applicable
Original User: jofuchs

Try changing your square brakets in your expression to normal brackets ()
Anthony


Thank you very much! That worked fine!
0 Kudos