Skip navigation
All People > Dan_Patterson > Py... blog > 2014 > July
2014

Py... blog

July 2014 Previous month Next month

This example shows how to create a dbf file, in a folder, and add fields and some sample data to it.  See the example setup after the line...

if __name__ == "__main__":

section of the script.  This script could easily be modified to accept command line parameters for the output filename.

 

'''
CreateTableDemo.py
  Author:
    Dan Patterson
    Dept of Geography and Environmental Studies
    Carleton University, Ottawa, Canada
    Dan.Patterson@carleton.ca
  Date created:  March 16, 2011
  Modified:      July 2013, Aug 2014
  Purpose:
    To demonstrate how to create tables using a simple function
  Requires:
    The user provides a table name and path, a list of fields and a list of data
    See the example setup after the line...    if __name__ == "__main__":
'''
def createTableFile (output_tbl, data_list, fieldsToAdd, arcpy):
  '''
    Requires:
    output_tbl  output feature class name "c:/temp/myfile.dbf"
    data_list   a list of lists of data eg.
                [[data list 1],[data list 2]...[data list n]]
            or  [[data list 1]]
    arcpy     the Geoprocessor Object
    Returns:
    Create the output table and returns a message (msg)
  '''
  fullName = os.path.split(output_tbl)
  outFolder = fullName[0].replace("\\","/")
  outFName =  fullName[1].replace(" ", "_")
  outFullName = outFolder + "/" + outFName
  msg = "\n"
  try:
    arcpy.CreateTable_management(outFolder, outFName)
    msg +=  "\nCreating:   " + str(outFName)
  except:
    msg += "\nFailed to create feature class:  " + arcpy.GetMessages()
    return msg
  for aField in fieldsToAdd:
    msg += "\nAdding field:  " + str(aField)
    try:
      arcpy.AddField_management(outFullName, aField[0], aField[1], aField[2], aField[3])
    except:
      msg += "\nFailed to add field: " + aField[0] + " " +arcpy.GetMessages()
  #
  #Create the insert cursor
  try:
    cur = arcpy.InsertCursor(output_tbl)
  except:
    msg += "Failed to create cursor"
    return msg
  anID=0
  for i in range(0,len(data_list)):
    values = data_list[i]
    a_row = cur.newRow()
    for j in range(0, len(values)):
      a_row.setValue(fieldsToAdd[j][0],values[j])
    cur.insertRow(a_row)
  del a_row
  del cur
  msg += "\nProcessing complete"
  return msg
#----------------------------------------------------------
if __name__ == "__main__":
  import sys, os
  import arcpy
  arcpy.env.overwriteOutput = True
  outDBF = "C:/temp/testdbf.dbf"      #!!!!!! change to suit or make into a parameter
  if os.path.exists(outDBF):
    os.remove(outDBF)
  #Sample data and fields to add to the table
  data_list = [[1,1,1,"a"],[2,2,2,"b"],[3,3,3,"c"],[4,4,4,"d"],[5,5,5,"e"]]
  fieldsToAdd = [["X", "double", 14, 7],
                 ["Y", "double", 14, 7],
                 ["Z", "double", 14, 7],
                 ["TextFld", "text", 20,""]]
  msg = createTableFile(outDBF, data_list, fieldsToAdd, arcpy)
  print msg

Update  2015-10-12

If you have installed ArcGIS Pro, then you have access to Python 3.4 which contains a useful statistics module... 9.7. statistics — Mathematical statistics functions — Python 3.4.3 documentation the focus provides some overlap with those presented here, but includes several useful sections dealing with centrality...specifically medians and mode. 

 

--------------------------------------------------------------------------------------------------

This is a fuller version of how to determine statistical calculations using numpy.  A variety of statistical parameters and frequency distributions are calculated in the example.  These functions work with 1-D and 2-D lists.  2-D lists are flattened to 1-D lists prior to calculation making it useful to get otherwise unavailable stats for such data as grids.

 

This class is used in the "Field Statistics" for ArcGIS for those that wish to work in that environment or to obtain source codes for this and other functions.  The code etc, can be found in:

 

1  ArcGIS Online at Field Statistics  (http://www.arcgis.com/home/item.html?id=6c384f06c9f14d09920f4ff14460f4e2),

2  in the attachment below

3  or at ObiDanGIS's Geomatics Blog: Statistical Calculations using Numpy .

 

 

The statistics include the usual but rarely quoted ones such mode, skewness and kurtosis by several means.  As well, functions to demonstrate how to determine several types of frequency distributions are presented.  The code includes some simple sample data so it can be run in standalone mode you can examine the outputs easily.  I make every attempt to write the code as verbose as possible so that non-programming students can view the logic contained in each function.  It also introduces the concept of classes in python for those that aren't familiar with it.  To use within your own code, examine the logic in the lines that follow the   if __name__ == "__main__":   section.

Sometimes the day is just too long and you need a break...a chuckle...something totally out there that will lift your spirits...to add some levity to your workday.   So I post this here with thanks to this-to-remain-nameless-individual's post in this thread ... called ...  The Intelevator from YouTube

  It is pure fun but it does show that sometimes people take themselves and their situations too seriously while others can roll with the punches.  So take a break...my current and former students...return to coding when you are done.