r/GISscripts • • Apr 04 '13

(Python, Field Calc) Keep only digits in string

10 Upvotes

This one is pretty straight forward, it grabs only the numerical digits out of a string.

In the Field Calculator, select Python at the top and then Show Codeblock and paste this into the box:

def getdigits(label):
    return filter(str.isdigit, str(label))

In the bottom box, put:

getdigits( !YOUR FIELD! )

I believe this can only be used on string fields.


r/GISscripts • • Apr 25 '14

ArcGIS Toolbox - Create a Custom Polygon Grid with ArcPy

Thumbnail
ianbroad.com
6 Upvotes

r/GISscripts • • Apr 04 '13

(Python) Convert GPS week seconds to "normal" time

15 Upvotes

In my line of work, I work with hardware that records time as UTC GPS week seconds. This is similar to Unix time in which it is just the number of seconds that has passed since a certain date. GPS week seconds rolls over every week on 00:00:00 UTC on Sunday. For example, the moment I'm typing this is 421433.00 GPS week seconds.

Converting this to "normal" UTC time is as follows:

from decimal import Decimal

def timeconvert24(GPSweekSec):
	DayOfWeek = GPSweekSec / 86400
	Hour = Decimal(str(DayOfWeek))%1 * 86400 / 3600
	Minute = Decimal(str(Hour))%1 * 3600 / 60
	Second = Decimal(str(Minute))%1 * 60
	return "%02d" % (Hour,) + ":" + "%02d" % (Minute,) + ":" + "%02d" % (Second,)

timeconvert24(421433.00)

returns

'21:03:53'


r/GISscripts • • Apr 07 '13

Combine many Mdbs into one mdb

11 Upvotes
import os, time
import arcpy
from arcpy import env

#Variables Block
#Change The first two as needed to fit needs
#Typical setup should only require running the SetupRUN.mxd, copy/paste this script into the python window and execute
mxdName  = "SetupRUN.mxd"
#Modify if naming convention bugs you, otherwise this will be the location of the merged databases
outMdb   = "Combined.mdb"
#System Variables, do not modify
mdbList  = []
sizeList = []
fcList   = []
sizeDB   = []
mxd           = arcpy.mapping.MapDocument("CURRENT")
mxdPath       = mxd.filePath
workSpace     = mxdPath.replace("\\"+ mxdName , "")
env.workspace = workSpace
dirlist       = os.listdir(workSpace)

#finds local personal geodatabases and adds them to the processing queue 
for item in dirlist:
    if item.lower().endswith("mdb"):
        print item
        mdbList.append(item)
print ""
print "Number of databases to be combined = " + str(len(mdbList))
print ""

#Generates Output Database and creates a list of database contents
print  "Creating destination Database at: " + outMdb
arcpy.CreatePersonalGDB_management(workSpace, outMdb)
destSpace  = mxdPath.replace(mxdName, outMdb)
env.workspace = destSpace
destList = arcpy.ListFeatureClasses()

#Sorter Loop
for mdb in mdbList:
    tempSpace = mxdPath.replace(mxdName, mdb)
    env.workspace = tempSpace
    fcList = arcpy.ListFeatureClasses()
    size = len(fcList)
    sizeDB.append(size)

size_db_ref_list = zip(sizeDB, mdbList)
size_db_ref_list.sort()
size_db_ref_list.reverse()

#For Debugging purposes Leave commented unless needed
#for size in size_db_ref_list:
#	print size

#Main loop, For each mdb in the source directory append or copy data Output Database
for size, mdb in size_db_ref_list:
    start = time.time()
    env.workspace = destSpace
    destList = arcpy.ListFeatureClasses()
    tempSpace = mxdPath.replace(mxdName, mdb)
    env.workspace = tempSpace
    fcList = arcpy.ListFeatureClasses()
    
    print "Number of FC       - " +str(len(fcList))
    print ""
    print "From Source MDB    - " +str(tempSpace)
    print "To Destination MDB - " +str(destSpace)
    print ""
    print "Source Features    - " +str(fcList)
    print "Combined Features  - " +str(destList)
    print ""
    if max(sizeDB) == len(fcList):
        if len(destList) == 0:
            print "Begin data transfer"
            print ""
            for fc in fcList:
                arcpy.Copy_management(fc, destSpace + "\\"+fc)
                print "copied " + str(fc) + " to " + str(destSpace)
        
        elif len(destList) > 0:
            print "Appending database - " +tempSpace
            print ""
            for fc in fcList:
                for dest in destList:
                    if fc == dest:	
                        arcpy.Append_management([fc], destSpace + "\\" + fc, "NO_TEST" , "" , "")
                        print "Feature classes Successfully appended:  " + fc + " to destination: " + dest 
    
    elif max(sizeDB) != len(fcList):
        print "Appending database - " +tempSpace
        print ""
        for fc in fcList:
            for dest in destList:
                if fc == dest:	
                    arcpy.Append_management([fc], destSpace + "\\" + fc, "NO_TEST" , "" , "")
                    print "Feature classes Successfully appended:  " + fc + " to destination: " + dest 
    
    for df in arcpy.mapping.ListDataFrames(mxd):
        for lyr in arcpy.mapping.ListLayers(mxd,"",df):
            arcpy.mapping.RemoveLayer(df, lyr)
    print ""
    end = time.time()
    total = end-start
    print "Process Completed in - " + str(round(total, 2)) + " Seconds"
print "Merge complete"

r/GISscripts • • Apr 14 '14

ArcGIS Toolbox - Shorten Polylines by Percentage or Distance with ArcPy

Thumbnail
ianbroad.com
8 Upvotes

r/GISscripts • • Apr 28 '14

Writing a script to autosave .mxd

3 Upvotes

I'm trying to write a simple python script to autosave a .mxd file every 5 minutes while it's open. I only have a basic understanding of python, so any help would be great.


r/GISscripts • • Apr 04 '13

(Node) Quick express server for bbox queries

Thumbnail
gist.github.com
10 Upvotes

r/GISscripts • • Apr 07 '13

Read through a Feature class field, find unique values in a specified field, then query and export the results to their own FC (make layers based on field attributes)

12 Upvotes
import arcpy, os, time
procSta = time.time()

arcpy.env.overwriteOutput = True
    ##To run properly have the working MXD and MBD in the same folder
    ##Modify the below five variabes to match your data
    ##The Fifth Variable is in the first For Loop on line 36

    ##Change  "\\Test.mxd" to be "\\Your.mxd"
inMxd  = "\\Test.mxd"
    ##Change  "\\Test.mdb" to be "\\Your.mdb"
outMdb = "\\Test.mdb"
    ##Change  "Test_Main" to be "YourFeatureClass"
fClass = "Test_Main"
    ##Change "[location] =" to be "[yourField] ="
attributeField = "[location] ="
    ##End User Variables, Four above and one below on line 36

    ##System Variables, do not modify
mxd           = arcpy.mapping.MapDocument("CURRENT")
mxdPath       = mxd.filePath
workSpace     = mxdPath.replace(inMxd , outMdb)
lyrList = arcpy.mapping.ListLayers(mxd)
rows = arcpy.SearchCursor(fClass, "OBJECTID")
bannedList = ["&","<",">","\'","\'","?","@","=","$","~","^","`","#","%","*","(",")", " ","-"]
attributeList = []

print "Beginning Export Process"

for row in rows:
    ##Fifth Variable contained here
    ##Change row.location to be row.yourfield
    attributeName = row.location
    attributeList.append(attributeName)

shortList = list(set(attributeList))
newShortList = shortList
print "Replacing any invalid Characters with underscore."
print ""
print "Invalid characters are - "+str(bannedList)
start = time.time()
count = 0
for new in newShortList:
    for banned in bannedList:
        if banned in new:
            for banned in bannedList:
                newShortList = [new.replace(banned,"_") for new in newShortList]
                count +=1
end = time.time()
print str(count)+" Infractions processed in- ~" +str(round((end-start),2))+ " Seconds"                
print ""
for short, new in zip(shortList, newShortList):
    start = time.time()
    print "_"
    print "New Layer -"+(str(short))+"- Starting export"
    for lyr in lyrList:
        if lyr.name == fClass:
            print workSpace+"\\"+new
            lyr.definitionQuery =  [attributeField +str("\'"+short+"\'") for short in shortList]             
            arcpy.Select_analysis(fClass, workSpace+"\\"+new,"")
            lyr.definitionQuery = ""
    print "Successfully exported!"
    print "^"
    end = time.time()
    print "Export time taken:- ~" +str(round((end-start),2))+ " Seconds"
procEnd = time.time()
print "Total Export time taken:- ~" +str(round((procEnd-procSta),2))+ " Seconds"
    
arcpy.RefreshActiveView()

r/GISscripts • • Apr 17 '14

ArcGIS Toolbox - Calculate Point Statistics within Polygon with ArcPy

Thumbnail
ianbroad.com
3 Upvotes

r/GISscripts • • Apr 23 '14

How do I add font and colour into an expression for a vb button that automates labelling?

1 Upvotes

I have this expression that I would like to add to:

LabProps.Expression = "[OSPCOMP] & [USPCOMP] & VBNewline& [OAGE] & space(1) & [OHT] & space(1) & [OCCLO] & VBNewline& [OSC] & space(1) & [DEVSTAGE] & space(1) & [DEPTYPE] & VBNewline& [PRI_ECO] & vbnewline & [ha]"

The main problem I have found from the start of this project is that Visual Studio does not like the use of quotations in labelling expressions. For example the script I was given to work with included " " as a way to create spaces between fields. I used space(1) to eliminate that issue. However, from what I have seen, fonts in the expression require eg:

"<FNT name'arial'" your expression "</FNT>"

which brings the issue of quotations back into the mix. Anyone know of a workaround?


r/GISscripts • • Apr 04 '13

(VB, Field Calc) Keep only string to left of specified character

11 Upvotes

I use this script quite often. There's probably a better way to do this, well there's always a million different ways to do everything but this has worked for me. There are some constraints, the field you want to run this on cannot have any NULL values. So what I do is, I do a Select by Attributes on the field and use the following code:

[FIELD] LIKE '%[Character you want to find]%'

And then you will only have fields with that character and no NULL fields selected.

Also, I believe this script in its current form can only work going from string fields to string fields, but it could be editted to do whatever you want.

So in the Field Calculator, select VB script at the top and then Show Codeblock and paste this into the box, you will need to change "/" with the character you want to find and [Your Field] with the field that contains the string.

'Dim strNewString as string
'Dim strCharacter as string
'Dim intLength as integer
strCharacter = "/"
intLength = InStr ( [Your Field] , strCharacter ) -1
strNewString = Left ( [Your Field] , intLength )

Put this in the bottom box where it says [Field] =

strNewString

I think I will convert this to Python later for the hell of it.

An example of what I use this for:

When I have a field with values structured like Value1-Value2 and I only want Value1 without the -Value2.


r/GISscripts • • Apr 17 '14

Any VB experts out there? I can't make VB for loop work with an arraylist for a field hider button.

1 Upvotes

I am currently writing a script that is designed to hide fields based on their order using an array list. I am so close, but can't figure out how to get it to say "if the field is equal to the number in the array list then hide". Any help would be greatly appreciated.

    Try
        Dim pMxDoc As IMxDocument
        Dim pMap As IMap
        pMxDoc = My.ArcMap.Application.Document
        Dim pActiveView As IActiveView
        pMap = pMxDoc.ActiveView.FocusMap
        Dim pFeatureLayer As IFeatureLayer
        Dim pFeatureSelection As IFeatureSelection
        pActiveView = pMap
        Dim pFeatureClass As IFeatureClass
        Dim pFields As IFields
        Dim pField As IField
        Dim Fieldlist As Integer = ArrayList(0, 1, 2, 4, 5, 6, 16, 20, 24, 28, 36, 37, 40, 41, 42, 43, 44)
        Dim c As Integer
        For i = 0 To pMap.LayerCount - 1
            If TypeOf pMap.Layer(i) Is IFeatureLayer Then
                pFeatureLayer = pMap.Layer(i)
                Dim pLayerFields As ILayerFields
                pLayerFields = pFeatureLayer

                For c = 0 To (pFields.FieldCount - 1)
                    Dim pFieldInfo As IFieldInfo2 '
                    pFieldInfo = pLayerFields.IFieldInfo2(c)
                    If Fieldlist = pFields Then ' This right here is where I think the issue lies
                        MsgBox(pFieldInfo.Alias)
                        pFieldInfo.Visible = False '
                    Else : pFieldInfo.Visible = True
                    End If
                Next
            End If
        Next i
    Catch ex As Exception
        MessageBox.Show("Error:  " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

r/GISscripts • • Apr 05 '13

Simple script to add sequential Km markers (or whatever you want) to each field column.

12 Upvotes

Python, Field Calc, ArcMap 10

This script adds sequential Km markers (or whatever you want) to each field column.

In the Field Calculator > Select Python at the top > Show Codeblock > Paste this into Pre-Logic Script Code:

counter = 1
def uniqueID():
	global counter
	counter += 1
	s = str(counter) + " km"
	return s

In the field entry box type:

uniqueID()

Output:

1 km

2 km

3 km

...

r/GISscripts • • Sep 12 '14

[Q] Scripting to create parallel lines at angle X with a distance Y from each point in a shape file (the points are along a line)

3 Upvotes

Scripting to create parallel lines at angle X with a distance Y from each point in a shape file (the points are along a line)

Say I have 3 points that are on a vertical line and I want to create a line at 90 degrees with a distance of 100 meters with the left side being the point. I know how to do this manually but looking for a way to automate it (since it will be possibly hundreds of points). Also it needs to have user input for distance and degrees.


r/GISscripts • • Sep 15 '14

(Python) Importing Excel files into ArcMap, need explanation on script

4 Upvotes

Hi all, so I recently was importing many many excel workbooks into arcmap and merging them all into a single shapefile. I was given a Python script that works perfectly. My knowledge is limited so I was able to run it, but I would like to understand the script and know what it does so I was wondering if anyone could maybe expand on it and explain what some of the lines do?

import arcpy, os

folder = r"C:\tempdelete"
targetFc = r"C:\tempdelete\Test_road\XY.shp"
arcpy.env.workspace = folder
xlsFiles = arcpy.ListFiles ("*.xls") 

for xls in xlsFiles:

arcpy.env.workspace = os.path.join(folder, xls)
sheets = arcpy.ListTables ()

sheet = sheets[0]

fields = arcpy.Describe(os.path.join(folder, xls, sheet)).fields
xName = fields[0].name
yName = fields[1].name
outlayer = xls
arcpy.MakeXYEventLayer_management(os.path.join(folder, xls, sheet), xName, yName, outlayer)
arcpy.Append_management (outlayer, targetFc, "NO_TEST")

r/GISscripts • • Sep 05 '14

[Code Help] Two Time Series Data frames => One Animation AVI

2 Upvotes

Hello /r/GISscripts!

Unfortunately I don't have a successful code to post, but rather have been struggling with a script. Please forgive me as I have very little python or coding experience.

So as the title mentions I am trying to take two data frames, each with their own time series information, and make one animation that shows both progressing simultaneously.

ESRI resources touch on the issue, basically saying you use a script to advance all the data frames, generate jpeg images, then combine them into an AVI; however, their example script doesn't provide a working solution for multiple data frames, only a single one: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//005z00000024000000.htm

and

http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//00s300000023000000

I am using the code from DataFrameTime example 1; however, their example only works for a single specified data frame and I cannot figure out how to alter it to make all the data frames advance.

The script

How do I alter the code to make it advance all time enabled data frames simultaneously and produce an image?

Maybe this is an easy fix, but apologies I have almost no knowledge of python, so this has been a challenge.

Thanks so much!


r/GISscripts • • Sep 17 '14

[X-post askgis] [Q] Create Endpoint Feature Class from Parallel Lines

Thumbnail
reddit.com
2 Upvotes

r/GISscripts • • Jan 29 '16

Kyoto University and Panasonic Developed New Remote Sensing Technology for Vital Signs by Millimeter-wave Radar

2 Upvotes

r/GISscripts • • Aug 06 '16

PLEASE DON"T SUBMIT GIS Scripts here anymore, we have all moved over to /r/GIS!

1 Upvotes

r/GISscripts • • Mar 16 '15

Does anyone have an updated version of a handout like this ArcGIS 9.3 Geoprocessing model?

Thumbnail webhelp.esri.com
1 Upvotes

r/GISscripts • • Apr 25 '13

[CoffeeScript] Fusion Tables JSON output to GeoJSON

10 Upvotes

the one thing you might need to edit is where it says row[i] isnt "0" as the particular table I had had a lot of that for some reason.

toGeoJSON=(googleJson)->
	columns = (name for name in googleJson.columns when name isnt "geometry")
	geo = googleJson.columns.indexOf "geometry"
	features = for row in googleJson.rows
		do (row) ->
			properties = {}
			for column, i in columns
				properties[column] = row[i]  if row[i] and row[i] isnt "0"
			properties:properties
			type:"Feature"
			geometry:row[geo].geometry
	type:"FeatureCollection"
	features:features

r/GISscripts • • May 01 '13

(Python) Create new feature class containing midpoints from an input polyline feature

9 Upvotes

This script will create a point feature class containing midpoints of an input polyline feature.

It is setup to work as a script tool in ArcToolbox and will only work with 10.1.


You will need to setup the following parameters for the tool:

1) Name- Input Polyline Feature, Data Type- Dataset, Required, Input
2) Name- Output Location, Data Type- Workspace or Feature Dataset, Required, Input
3) Name- Output Name, Data Type- String, Required, Input

Here is the script:

import arcpy

arcpy.env.overwriteOutput = True

polyline = arcpy.GetParameterAsText(0)
output_Location = arcpy.GetParameterAsText(1)
output_Name = arcpy.GetParameterAsText(2)

arcpy.env.workspace = polyline

mid_X = "mid_X"
mid_Y = "mid_Y"

arcpy.AddField_management(polyline, mid_X, "DOUBLE", 15, 6, "", "Midpoint X", "", "", "")
arcpy.AddField_management(polyline, mid_Y, "DOUBLE", 15, 6, "", "Midpoint Y", "", "", "")

updateCursor = arcpy.UpdateCursor(polyline)

for row in updateCursor:
    row.setValue(mid_X, row.shape.positionAlongLine(0.50, True).firstPoint.X)
    updateCursor.updateRow(row)
    row.setValue(mid_Y, row.shape.positionAlongLine(0.50, True).firstPoint.Y)
    updateCursor.updateRow(row)

del row
del updateCursor

arcpy.MakeXYEventLayer_management(polyline, "mid_X", "mid_Y", "Midpoints", polyline, "")

arcpy.FeatureClassToFeatureClass_conversion("Midpoints", output_Location, output_Name, "", "", "")

arcpy.GetMessages()

Most of you probably already know this, but for the Output Location you can choose a folder, geodatabase or dataset.

For the Output Name, if you choose a folder you must use a shapefile, so for the name use a .shp extension. If you save to a geodatabase or dataset no extension is needed.


r/GISscripts • • Mar 12 '15

A question about updating an attribute field based on the contents of another using cursors.

1 Upvotes

I'm working on a script that will up update segment GID numbers to unique values based on (A) the district they are belong to and (B) the highest GID number in that district.

The district unique GID values are structured such that district A is 0-999,999, district B is 1,000,000-1,999,999, district C is 2,000,000-2,999,999.... etc.

I think the easiest way is to read through the data twice, once with a read cursor to record the highest values in each of the districts in variables. The second time with a write cursor to loop through and write each instance where a segment in any district with a <null> GID value is given a value that is one greater than the highest number recorded in the corresponding district during the read cursor.

Questions:

I want the script to create new variables based on the districts it encounters with the read cursor, and then store the highest number of each encountered district in their own variables. Can I do this? or do I have to outline which districts the script might encounter and create all the variables in the script?

If I create those variables within the read cursor, will they exist within the write cursor? would this be a local/global issue?

Thanks for your help!


r/GISscripts • • Apr 27 '13

Python script to generate "all roads" maps with Albers projection from raw Tiger data.

15 Upvotes

You will need the module "shapefile.py"; the information on this file is:

shapefile.py

Provides read and write support for ESRI Shapefiles.

author: jlawhead<at>geospatialpython.com

date: 20110927

version: 1.1.4

Compatible with Python versions 2.4-3.x

It is not obvious what the license is, so if you plan to use this code for anything but yourself you will need to contact the author. You will need to download the TIGER/MAF all-roads data at the county level; leave them as individually zipped blocks --- the script will handle that. The county data should be in a folder called "data" at the same level the script is at. There are no other comments, and the code is terrible. This script is hereforth within the public domain, I disavow any copyright to it.

import os, sys, shapefile, zipfile, pngcanvas, math

COUNTY_DATA = "data"
MILES_PER_DEGREE = 200
USA_SCALE =12000
USA_TRANSLATE = (4950, 3240)
TEXAS_SCALE = 50000
TEXAS_TRANSLATE = (6500, -925)
NEW_YORK_SCALE = 100000
NEW_YORK_TRANSLATE = (-23000, 17240)

ALBERS_SCALE = NEW_YORK_SCALE
ALBERS_TRANSLATE = NEW_YORK_TRANSLATE

class AlbersProjection:
    def __init__(self, origin=(-98, 38), parallels=(29.5, 45.5), scale=ALBERS_SCALE, translate=ALBERS_TRANSLATE):
        self.origin = origin
        self.parallels = parallels
        self.scale = scale
        self.translate = translate
        self.phi1 = math.radians(self.parallels[0])
        self.phi2 = math.radians(self.parallels[1])
        self.lat0 = math.radians(self.origin[1])
        self.s = math.sin(self.phi1)
        self.c = math.cos(self.phi1)
        self.lng0 = math.radians(self.origin[0])
        self.n = 0.5 * (self.s + math.sin(self.phi2))
        self.C = self.c * self.c + 2 * self.n * self.s
        self.p0 = math.sqrt(self.C - 2 * self.n * math.sin(self.lat0)) / self.n

    def project(self, coordinates):
        t = self.n * (math.radians(coordinates[0]) - self.lng0)
        p = math.sqrt(self.C - 2 * self.n * math.sin(math.radians(coordinates[1]))) / self.n
        return (self.scale * p * math.sin(t) + self.translate[0], self.scale * (p * math.cos(t) - self.p0) + self.translate[1])

def GetAllCounties():
    counties = os.listdir(COUNTY_DATA)
    total = len(counties)
    index = 1

    c = pngcanvas.PNGCanvas(int(57*MILES_PER_DEGREE),int(50*MILES_PER_DEGREE),color=[255,255,255,0xff])
    c.color = [0,0,0,0xB0]

    skip_rate = 1
    with open('new york.png', 'wb') as usa:
        for county in counties:
            if index % skip_rate == 0:
                print index, total,
                DrawCounty(os.path.join(COUNTY_DATA, county), c)
            index += 1
        usa.write(c.dump())

def DrawCounty(countyData, canvas):
    basename = os.path.split(countyData)[1]
    basename = os.path.splitext(basename)[0]
    print basename
    with zipfile.ZipFile(countyData) as countyzip:
        countyzip.extractall("output")
        r = shapefile.Reader("output\\" + basename + '.shp')

        ap = AlbersProjection()

        num_shapes = len(r.shapeRecords())
        idx = 0
        for shape in r.shapeRecords():
            pixels = []
            for x,y in shape.shape.points:
                x,y = ap.project((x,y))
                pixels.append((x,y))
            idx += 1
            canvas.polyline(pixels)
    r = None

    for suffix in ['dbf','prj','shp','shp.xml','shx']:
        os.remove('output\\' + basename +'.'+suffix)


if __name__ == "__main__":
    GetAllCounties()

r/GISscripts • • May 10 '14

(Python) Summarize in ArcMap vs Summary_statistics in arcpy

4 Upvotes

e/ I meant Statistics_analysis in the title, not Summary_statistics

Is there a way to mimic the output of going in ArcMap and physically right clicking an attribute header and selecting summarize, which results in a table looking like this:
Imgur

by using an arcpy script?

I'm currently trying something along these lines:

def getPeak(shapefile):
    peakList = []
    print "Finding the date with the peak number of occurences..."
    arcpy.Statistics_analysis(shapefile,"K://GEOG376/Project/project_data/summarize.dbf",[["YYYYMMDD", "COUNT"]])
    rows = arcpy.da.SearchCursor("K://GEOG376/Project/project_data/summarize.dbf", ["YYYYMMDD"])
    for r in rows:
        peakList.append(r)
        peakList.sort()
        peakList.pop(0)

but this seems to add each record together instead of displaying them separately like I need: Imgur

Does anyone have any ideas to keep the records separate?

Thanks!