shapefile是GIS中一种数据类型,在ArcGIS中被称为要素类(Feature Classes),主要包括点(point)、线(polyline)和多边形(polygon)。
解析geopandas文件的方式很多,本文介绍两个 pyshp和geopandas。
1.pyshp(Python Shapefile Library)
是一个Python库,用于在Python脚本中对ArcGIS中的Shapefile文件(.shp,.shx,.dbf等格式)进行读写操作。
安装:pip install pyshp
解析:
Reader类, 对shapefile文件读取;Editor类,对shapefile文件编辑;Writer类,对shapefile文件写操作
每个文件包含 "几何数据"(Geometry)和"属性数据"(Attribute Record) ,两个文件数据一一对应。
import shapefile
tpath = 'D:\\work2017\\china_train\\china-shp\\train\\rai_4m.shp'
sf = shapefile.Reader(tpath)
shapes = sf.shapes()
每个几何对象包含有4个属性:数据类型(shapeType),代表该"几何数据"对象的数据类型(点,shapeType=1,线,shapeType=3,多边形,shapeType=5);数据范围(bbox),只针对多点数据,代表该"几何数据"对象的边界范围;数据块(parts),只针对线或者多边形,代表该"几何数据"对象各个块的第一个点的索引;点集(points),代表该"几何数据"对象的所有点坐标。 "属性数据"即每个"几何数据"对象在属性表中的对应项。
属性数据就是一个二维数据
recds = sf.records()
for i in recds:
print i[9]
解析后一行属性的结果:
<type 'list'>: [2.4675391, 9.0042706, 2, 3, '30000', '232723', '\xc4\xae\xba\xd3\xcf\xd8', '23', '27', '23', 52.933796, 122.69707]
2. geopandas
它是以pandas的模式对 shp文件的封装,使用起来更方便。
安装:conda install -c conda-forge geopandas
依赖库需要c++环境,如果还是用 pip安装,可能会安装不成功。
解析与展示:
%matplotlib inline
import shapely, geopandas, fiona
import seaborn as sns
from fiona.crs import from_epsg,from_string
tpath = 'D:\\work2017\\china_train\\china-shp\\train\\rai_4m.shp'
shp_df = geopandas.GeoDataFrame.from_file(tpath,encoding = 'gb18030')
shp_df.head()
shp_df.plot()
解析后数据:
展示图形:
参考:
1.Using geopandas on Windows
http://geoffboeing.com/2014/09/using-geopandas-windows/
2.shapefile+matplotlib
https://stackoverflow.com/questions/15968762/shapefile-and-matplotlib-plot-polygon-collection-of-shapefile-coordinates
3.用Python做地图投影
http://www.jianshu.com/p/241546a36a93