Arcmap支持名为arcpy的Python库。正如我们所知,Pandas的工作方式类似于Excel,可以轻松地读取和处理数据。是的,有时它也可以用来导出.xls和.xlsx文件。我编写了一个函数,用于将Pandas的DataFrame和Arcmap的shp文件进行相互转换。代码如下:
def Shp2dataframe(path):
fields=arcpy.ListFields(path)
table=[]
fieldname=[field.name for field in fields]
data=arcpy.SearchCursor(path)
for row in data:
r=[]
for field in fields:
r.append(row.getValue(field.name))
table.append(r)
return pd.DataFrame(table,columns=fieldname)
'''Fuction:
make the table of pandas's DataFrame convert to the shp of esri
Input:
df -- pandas DataFrame from the shp converted
outpath -- the shp output path
geometryType -- the type of geomentey, eg:'POINT','POLYLINE','POLYGON','MULTIPOINT'
temple -- the temple, at most time it is used the DataFrame's shp
'''
def Dataframe2ShpTemplate(df,outpath,geoType,template):
out_path = outpath.replace(outpath.split('/')[-1],'')
out_name = outpath.split('/')[-1]
geometry_type = geoType
feature_class = arcpy.CreateFeatureclass_management(
out_path, out_name, geometry_type, template)
desc = arcpy.Describe(outpath)
if template=='':
fields = set(list(df.columns)+['Shape','FID'])
originfieldnames = [field.name for field in desc.fields]
for fieldname in fields:
if fieldname not in originfieldnames:
arcpy.AddField_management(outpath,fieldname,'TEXT')
for row in df.index:
df['SHAPE@'] = df['Shape']
cursor = arcpy.da.InsertCursor(outpath,[field for field in df.columns])
cursor.insertRow([df[field][row] for field in df.columns])
print 'Pandas to shp finish!'
del cursor