Hi,
I have another question for today - automatic renaming values in ModelBuilder?
My table have attributes looks like this:
FID CODE CODE2
1 1001 1
2 1001 1
3 2000 1
4 2000 1
5 2000 1
...........and so on.
And my goal is - that column CODE2 will be automatically calculated.
So, there are two polygons with CODE 1001 but CODE2 is different for each of these.
FID CODE CODE2
1 1001 1
2 1001 2
3 2000 1
4 2000 2
5 2000 3
.....
Is there some possibility to do this?
Thank you.
Solved! Go to Solution.
OK, so run a field calculator ensuring that Python is chosen as the expression type.
pre-logic script code/ Code block:
CODE_dict = {}
def auto_increment(field):
global CODE_dict
if field in CODE_dict.keys():
CODE_dict[field] += 1
return CODE_dict[field]
else:
CODE_dict[field] = 1
return 1
to run it using that function:
auto_increment(!CODE!)
The code block creates a global dictionary to store a key of the CODE against an increment. If no key exists in the dictionary, the key(CODE) is added to it, with a value of 1. This is also then returned by the function.
If the key(CODE) does exist in the dictionary, the value is then incremented by 1, and that value returned.
I would suggest a Python field calculation. I've never come across anything to automatically do something like that.
If your data is ordered by FID, will it always be ordered by CODE? i.e. will it always follow the logical structure you provided in the example?
FID CODE CODE2
1 1001 1
2 1001 2
3 2000 1
4 1001 3
5 2000 2
If not, is the order of assignment of auto-incremented values important? i.e. would you be happy if the lowest FID had the highest increment or that it was random?
FID CODE CODE2
1 1001 2
2 1001 1
3 2000 3
4 2000 1
5 2000 2
Yes, it does not really matter. That CODE2 is just needed for differentiate polygons with label CODE.
OK, so run a field calculator ensuring that Python is chosen as the expression type.
pre-logic script code/ Code block:
CODE_dict = {}
def auto_increment(field):
global CODE_dict
if field in CODE_dict.keys():
CODE_dict[field] += 1
return CODE_dict[field]
else:
CODE_dict[field] = 1
return 1
to run it using that function:
auto_increment(!CODE!)
The code block creates a global dictionary to store a key of the CODE against an increment. If no key exists in the dictionary, the key(CODE) is added to it, with a value of 1. This is also then returned by the function.
If the key(CODE) does exist in the dictionary, the value is then incremented by 1, and that value returned.
yay!
that´s exactly what I was looking for the whole day 🙂 thank you.