首页 > 代码库 > python-快速入门

python-快速入门

ref: Calculate Field examples

Entering values with the keyboard is not the only way you can edit values in a table. In some cases, you might want to perform a mathematical calculation to set a field value for a single record or even all records. You can perform simple as well as advanced calculations on all or selected records. In addition, you can calculate area, length, perimeter, and other geometric properties on fields in attribute tables. The sections below include examples of using the field calculator. Calculations can be performed using either Python or VBScript.

Python is the recommended scripting language for ArcGIS. Use Python if you want access to geoprocessing functionality, including feature geometry. The adoption of Python as the scripting language for ArcGIS 10.0 provides many opportunities for performing calculations.

NoteNote:
  • Python enforces indentation as part of the syntax. Use two or four spaces to define each logical level. Align the beginning and end of statement blocks, and be consistent.
  • Python calculation expression fields are enclosed with exclamation points (!!).
  • When naming variables, note that Python is case sensitive, so yield is not the same as Yield.
  • After entering statements, you can click Save if you want to write them to a file. The Load button will prompt you to find and select an existing calculation file.

Simple calculations

Simple string examples

Strings are supported by a series of Python string functions, including capitalize, rstrip, and replace.

Capitalize the first character of the string in the field CITY_NAME.

!CITY_NAME!.capitalize()

Strip any white space from the end of the string in the field CITY_NAME.

!CITY_NAME!.rstrip()

Replace any occurrences of "california" with "California" found in the field STATE_NAME.

!STATE_NAME!.replace("california", "California")

Characters in a string field can be accessed by indexing and slicing in Python. Indexing fetches characters at an index position; slicing fetches a group of characters.

ExampleExplanationResult
!fieldname![0]The first character."a"
!fieldname![-2]The second-last character."e"
!fieldname![1:4]The second, third, fourth, and fifth characters."bcd"
 

Python also supports the string formatting using the % operator.

Combine FieldA and FieldB separated by a colon.

"%s:%s" % (!FieldA!, !FieldB!)
Common Python string operations

Simple math examples

Python provides tools for processing numbers. Python also supports a number of numeric and mathematical functions, including math, cmath, decimal, random, itertools, functools, and operator.

OperatorExplanationExampleResult
x + yx plus y1.5 + 2.54
x - yx minus y3.3 - 2.21.1
x * yx times y2.0 * 2.24.4
x / yx divided by y4.0 / 1.253.2
x // yx divided by y (floor division)4.0 / 1.253
x % yx modulo y8 % 32
-xnegative expression of xx = 5-5
 
-x
+xx is unchangedx = 55
 
+x
x ** yx raised to the power of y2 ** 38
 

Multiplication

!Rank! * 2

Calculate volume of a sphere given a radius field.

4 / 3 * math.pi * !Radius! ** 3

Using code blocks

With Python expressions and the Code Block parameter, you can:

  • Use any Python function in the expression.
  • Access geoprocessing functions and objects.
  • Access properties of feature geometry.
  • Access the new random value operator.
  • Reclassify values using if-then-else logic.
  • Use other geoprocessing tools.

How the code block is used is determined by the parser used. The Field Calculator supports Python and VB Script parsers.

Parser

Code Block

Python

Supports Python functionality. The code block is expressed using Python functions (def). Geometry properties are expressed using geoprocessing objects such as Point objects where appropriate.

VB Script

Calculations are performed using VBScript.

Python functions are defined using the def keyword followed by the name of the function and the function’s input parameters. Values are returned from the function using a return statement. The function name is your choice (don‘t use spaces or leading numbers).

Using the field calculator
NoteNote:

Remember, Python enforces indentation as part of the syntax. Use two or four spaces to define each logical level. Align the beginning and end of statement blocks, and be consistent.

Code samples–math

Round a field‘s value to two decimal places.

Expression:
round(!area!,2)
Parser:Python

Use the math module to help convert meters to feet. The conversion is raised to the power of 2 and multiplied by the area.

Parser:PythonExpression:
MetersToFeet((float!shape.area))
Code Block:
1 def MetersToFeet(area):2   return math.pow(3.2808,2) * area
View Code

Calculate fields using logic with Python

Classify based on field values.

Parser:PythonExpression:
Reclass(!WELL_YIELD!)
Code Block:
1 def Reclass(WellYield):2   if (WellYield >= 0 and WellYield <= 10):3     return 14   elif (WellYield > 10 and WellYield <= 20):5     return 26   elif (WellYield > 20 and WellYield <= 30):7     return 38   elif (WellYield > 30):9     return 4
View Code

Code samples–geometry

NoteNote:

For more on converting geometry units, see the section ‘Geometry unit conversions‘ below.

Calculate the area of a feature.

Parser:PythonExpression:
!shape.area!

Calculate the maximum X-coordinate of a feature.

Parser:PythonExpression:
!shape.extent.XMax!

Calculate the vertex count of a feature.

Parser:PythonExpression:
MySub(!shape!)
Code Block:
 1 def MySub(feat):     2  partnum = 0 3  4  # Count the number of points in the current multipart feature 5  partcount = feat.partCount 6  pntcount = 0 7  8  # Enter while loop for each part in the feature (if a singlepart feature 9  # this will occur only once)10  #11  while partnum < partcount:12   part = feat.getPart(partnum)13   pnt = part.next()14 15   # Enter while loop for each vertex16   #17   while pnt:18    pntcount += 1   19    pnt = part.next()20    21    # If pnt is null, either the part is finished or there is an 22    # interior ring23    #24    if not pnt: 25     pnt = part.next()26   partnum += 127  return pntcount
View Code

For a point feature class, shift the x coordinate of each point by 100.

Parser:PythonExpression:
shiftXCoordinate(!SHAPE!)
Code Block:
1 def shiftXCoordinate(shape):2    shiftValue = http://www.mamicode.com/100"color: #008080;">3    point = shape.getPart(0)4    point.X += shiftValue5    return point
View Code

Geometry unit conversions

Shape and length properties of the geometry field can be modified with unit types expressed with an @ sign.

  • Areal unit of measure keywords:
    • ACRES | ARES | HECTARES | SQUARECENTIMETERS | SQUAREDECIMETERS | SQUAREINCHES | SQUAREFEET | SQUAREKILOMETERS | SQUAREMETERS | SQUAREMILES | SQUAREMILLIMETERS | SQUAREYARDS | SQUAREMAPUNITS | UNKNOWN
  • Linear unit of measure keywords:
    • CENTIMETERS | DECIMALDEGREES | DECIMETERS | FEET | INCHES | KILOMETERS | METERS | MILES | MILLIMETERS | NAUTICALMILES | POINTS | UNKNOWN | YARDS
NoteNote:

If the data is stored in a geographic coordinate system and a linear unit (for example, feet) is supplied, the length calculation will be converted using a geodesic algorithm.

CautionCaution:

Converting the areal units on data in a geographic coordinate system will yield questionable results since decimal degrees are not consistent across the globe.

Calculate a feature‘s length in yards.

Parser:PythonExpression:
!shape.length@yards!

Calculate a feature‘s area in acres.

Parser:PythonExpression:
!shape.area@acres!

Code samples–dates

Calculate the current date.

Parser:PythonExpression:
time.strftime("%d/%m/%Y")

Calculate the current date and time.

Parser:PythonExpression:
time.strftime("%d/%m/%Y %H:%M")

Code samples–strings

Return the three right-most characters.

Parser:PythonExpression:
!SUB_REGION![-3:]

Replace any cases of an uppercase "P" with a lowercase "p".

Parser:PythonExpression:
!STATE_NAME!.replace("P","p")

Concatenate two fields with a space separator

Parser:PythonExpression:
!SUB_REGION! + " " + !STATE_ABBR!

Convert to proper case

The following examples show different ways to convert words so that each word has the first character capitalized and the rest of the letters in lowercase.

Parser:PythonExpression:
 .join([i.capitalize() for i in !STATE_NAME!.split( )])
Parser:PythonExpression:
 1 string.capwords(!STATE_NAME!,  ) 2  3 Expression Type: 4 import string 5  6 Parser: 7 Python 8  9 Expression:10 MySub(!STATE_NAME!)11 12 Code Block:13 def MySub(myfieldname):14  import string 15  return string.capwords(myfieldname,  )
View Code

Accumulative and sequential calculations

Calculate a sequential ID or number based on an interval.

Parser:PythonExpression:
autoIncrement()
Code Block:
 1 rec=0 2 def autoIncrement(): 3  global rec 4  pStart = 1 #adjust start value, if req‘d  5  pInterval = 1 #adjust interval value, if req‘d 6  if (rec == 0):  7   rec = pStart  8  else:  9   rec = rec + pInterval 10  return rec
View Code

Calculate the accumulative value of a numeric field.

Parser:PythonExpression:
accumulate(!FieldA!)
Code Block:
1 total = 02 def accumulate(increment):3  global total4  if total:5   total += increment6  else:7   total = increment8  return total
View Code

Calculate the percentage increase of a numeric field.

Parser:PythonExpression:
percentIncrease(float(!FieldA!))

 Code Block:

1 lastValue =http://www.mamicode.com/ 02 def percentIncrease(newValue):3  global lastValue4  if lastValue:5   percentage = ((newValue - lastValue) / lastValue)  * 1006  else: 7   percentage = 08  lastValue =http://www.mamicode.com/ newValue9  return percentage
View Code

Random values

Use the numpy site-package to calculate random float values between 0.0 and 1.0.

Parser:PythonExpression:
getRandomValue()
Code Block:
1 import numpy.random as R2  3 def getRandomValue():4     return R.random()
View Code

python-快速入门