Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I have two columns in a personal geodatabase table that I'm trying to add up (to a third field) using a python function in field calculator, however some of the string values are not real numbers.

e.g.

field1     field2
12.24      2
h3.3       4
xyz        1
932.33.32  3

I have a conditional statement that checks for letters, however I'm stuck on how to check for the two decimal character occurrence,

932.33.32

For the two decimal string example I just want to return the value of field2. Here is my code so far.

import re
def cal(field1, field2):
  #check for two decimal character occurrence
  elif re.search('[0-9]+', x):
    myvalue = float(field1) + float(field2)
    return myvalue
  else: 
    myvaluefinal = float(field1) + float(field2)
    return myvaluefinal

Thank You

share|improve this question

2 Answers 2

up vote 3 down vote accepted

I figured out another way to do it, see code below:

def cal(x, x2):
  def isfloat(str):
    try: float(x)
    except ValueError: return False
    return True
  checkfloat = isfloat(x)
  if checkfloat == False:
    return x2
  elif checkfloat == True:
    myvaluefinal = float(x) + float(x2)
    return myvaluefinal
share|improve this answer
1  
Is there any way the re.search part of this code will ever be executed? –  whuber Jul 30 '12 at 15:13
    
@whuber, No I removed it, thanks. –  artwork21 Jul 31 '12 at 2:35

Given your use case, you could test for a "two decimal string" like this:

str_test = '123.456.789'
if len(str_test.split('.')[0::1]) == 3:
    print 'This is a string which contains two decimals... do something'

You would of course want to build in some more elaborate type and formatting logic, but this is the general idea.

share|improve this answer
    
Thanks, your code does work, however I could not figure out how to include it into my function. I posted another way to do it. –  artwork21 Jul 30 '12 at 14:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.