首页 > 其他 > 详细

DataFrame与shp文件相互转换

时间:2015-06-06 13:38:06      阅读:232      评论:0      收藏:0      [点我收藏+]

因为习惯了使用pandas的DataFrame数据结构,同时pandas作为一个方便计算和表操作的数据结构具有十分显著的优势,甚至很多时候dataFrame可以作为excel在使用,而在用python操作gis的shp文件时很不顺畅,不太符合使用习惯,故写了一个DataFrame与arcgis地理文件相互转换的函数,这个处理起来可以节约大量的思考时间。

Shp转DataFrame:

import arcpy
import pandas as pd
def Shp2dataframe(path):
    ‘‘‘将arcpy表单变为pandas表单输出‘‘‘
    fields=arcpy.ListFields(path)
    table=[]
    fieldname=[field.name for field in fields]
    #游标集合,用for 循环一次后没办法循环第二次!一个游标实例只能循环一次
    data=arcpy.SearchCursor(path)
    for row in data:
        #Shape字段中的要数是一个几何类
        r=[]
        for field in fields:
            r.append(row.getValue(field.name))
        table.append(r)
    return pd.DataFrame(table,columns=fieldname)

DataFrame转Shp:

DataFrame转Shp采用了模板形式,通过模板建立字段文件,坐标系等可以更加快速构建字段。

#将由ReadTable读取的pandas表转换为shp格式,template为模板
def Dataframe2ShpTemplate(df,outpath,geoType,template):
    ‘‘‘
    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
    ‘‘‘
    out_path = outpath.replace(outpath.split(‘/‘)[-1],‘‘)
    out_name = outpath.split(‘/‘)[-1]
    geometry_type = geoType
    #template为模板,可以将里面属性全部赋予新建的要素,包括字段、坐标系
    feature_class = arcpy.CreateFeatureclass_management(
        out_path, out_name, geometry_type, template)
    #‘*‘表示插入所有字段,但如果不用模板容易产生位置不对等
    #cursor = arcpy.da.InsertCursor(outpath,‘*‘)
    for row in df.index:
        #Shape需要改为‘SHAPE@‘才可以写入
        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

DataFrame与shp文件相互转换

原文:http://my.oschina.net/Kanonpy/blog/425633

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!