4

My problem is the following. I have a huge dataset of forest stands. All the information are separated but in many cases the stands have different age and this is marked in one attribute for example

age = 14/2

This marks that one part of the stand is 140 years old and the rest 20 years.

My problem is that I need to have these two values separate, optimally in two colums:

age 1 = 14
age 2 = 2

Also, not always is the first number consisted of two digits, and vice versa.

Any ideas how I can do it? I was thinking of using FieldPyCalculator, but I'm not any good with Python.

3 Answers 3

5

If you just want to split this string into two integers you can use the Python split function and convert the resulting two list entrys from type string to type integer.

age = '14/2'
ages = age.split("/")
age 1 = int(ages[0])
age 2 = int(ages[1])

or as a function:

def split_age(self, age):
    return(int(age.split("/")[0]), int(age.split("/")[1]))

This function would return a touple of age integers.

1
  • Martin, than you very much, this works very well.
    – Meto
    Feb 6, 2015 at 14:18
2

Great answer by @Martin! Alternatively, you can also achieve this via the normal Field Calculator by using the following commands:

When creating the column age 1:

regexp_replace("Age" , '/[0-9]*', '')

When creating the column age 2:

regexp_replace("Age" , '[0-9]*/', '')

Note: Make sure to place the forward slash / at the beginning if you want to exclude all terms after it; place / at the end to exclude all terms before it.

2
  • 1
    I don't know if this is working in the field calculator but with regex you can use [0-9]* to look for n numbers until a char.
    – Martin
    Feb 6, 2015 at 14:15
  • @Martin, brilliant! Yup, it works like a charm. Thank you for that, I learnt something :)
    – Joseph
    Feb 6, 2015 at 14:20
1

One more option using the Field Calculator,

For age1,

left("Age", length("Age") -  strpos("Age" ,'/'))

For age2,

right("Age", length("Age") - strpos("Age" ,'/')-1)
1
  • Another very good method, I never used the left and right operations before but great to see how it applies here!
    – Joseph
    Feb 6, 2015 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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