-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAddAreas_exportToTable.py
executable file
·98 lines (78 loc) · 2.91 KB
/
AddAreas_exportToTable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'''
Created on Mar 9, 2016
@author: TIMOTHYJOHNSON
This scripts calculates the area of each polygon for ~12000 shapefiles,
adding an area column, then the tables from each shapefile are converted to
csv files, then stacked using pandas
'''
# Import system modules
from __future__ import division
import arcpy
from arcpy import env
from arcpy.sa import *
import os, sys, csv, time
import pandas as pd
import glob
pathlist = [r"F:\TimData\CGIAR_CRP\Biodiversity_DB" + "\\",
r"F:\TimData\CGIAR_CRP\Biodiversity_DB\IndividualShapefiles"
r"\dissolve" + "\\",
r"F:\TimData\CGIAR_CRP\Biodiversity_DB\IndividualShapefiles"
r"\csvs" + "\\"]
start_time = time.time()
arcpy.env.overwriteOutput = True
arcpy.CheckOutExtension("Spatial")
def makefiles():
'''create folders if they do not already exist
'''
for files in pathlist:
if not os.path.exists(files):
os.makedirs(files)
print "made " + files
def addArea():
'''add area fields to all dissolved shapefiles'''
env.workspace = pathlist[1]
polylist = arcpy.ListFeatureClasses()
for poly in polylist:
try:
arcpy.AddGeometryAttributes_management(poly, "AREA_GEODESIC", "#",
"SQUARE_KILOMETERS")
print "Finished adding area for:", poly
except Exception:
print "Encountered error with", poly
print arcpy.GetMessages()
pass
def exportToCsvs():
'''exports every shapefile to csv'''
env.workspace = pathlist[1]
polylist = arcpy.ListFeatureClasses()
for poly in polylist:
try:
outname = str(poly)[:-9]+".csv"
print outname
arcpy.ExportXYv_stats(poly,["SCINAME","AREA_GEO"], "COMMA",
pathlist[2]+outname, "ADD_FIELD_NAMES")
print "Finished exporting:", outname
except Exception:
print "Encountered error with", outname
print arcpy.GetMessages()
pass
def stackdata():
alltxts = glob.glob(pathlist[2] + "/*.csv") # grab all csv files in list
firsttxt = alltxts[:1] # text to append the others to
totaldf = pd.read_csv(firsttxt[0])
testtxts = alltxts[1:] # list of every csv except the first
for txt in testtxts:
df = pd.read_csv(txt)
totaldf = totaldf.append(df) # append every csv to one another in list
print "Finished", txt
return totaldf
def main():
makefiles()
addArea()
exportToCsvs()
stackedcsv = stackdata()
stackedcsv.to_csv(pathlist[0] + 'TotalStackedBirdData_Areas.csv')
if __name__ == "__main__":
main()
#Print out time of finish and verify success of finish
print (time.time() - start_time) / 60, "minutes, finished"