從pandas到geopandas

(歡迎轉載,須要保留文末的我的微信公衆號二維碼)python

pandas簡介

Pandas是Python的一個結構化數據分析的利器。其中,DataFrame是比較經常使用的處理數據的對象,相似於一個數據庫裏的table或者excel中的worksheet,能夠很是方便的對二維數據讀取(xls,csv,hdf等)、增刪改查、基本繪圖等。pandas應該是用python作數據分析必不可少的工具。git

看一個dataframe的實例github

geopandas簡介

DataFrame至關於GIS數據中的一張屬性表,爲了將pandas的特性用到空間數據,就有了geopandas。其目標是使得在python中操做地理數據更方便。數據庫

Pandas is an open source project to make working with geospatial data in python easier. GeoPandas extends the datatypes used by pandas to allow spatial operations on geometric types. Geometric operations are performed by shapely. Geopandas further depends on fiona for file access and descartes and matplotlib for plotting.json

geopandas結合了pandas和shapely的功能,擴展了pandas在空間數據操做方面的能力,從而使得你能夠輕鬆的用python實現空間數據分析。微信

看一個geodataframe的實例dom

與dataframe相對,直觀的區別是多了一個geometry的字段。工具

安裝

pip install geopandas
# or
conda install -c conda-forge geopandas

官網示例

先直接照搬一個官網上的例子編碼

p1 = Polygon([(0, 0), (1, 0), (1, 1)])
p2 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
p3 = Polygon([(2, 0), (3, 0), (3, 1), (2, 1)])
g = gpd.GeoSeries([p1, p2, p3])
g.plot()

能夠很是方便的計算面積和緩衝區spa

print g.area
g.buffer(0.5).plot()

還有其餘空間數據分析的功能,有興趣能夠去官網瞭解下。

示例2. 構建geodataframe對象

gepandas提供了多個讀取矢量空間數據的接口,支持包括shapefile,geojson等。也支持直接從已有的dataframe對象生成geodataframe,示例以下:

df = pd.DataFrame(np.random.randn(50, 3),columns=['X', 'Y', 'Z'])
geom = [shapely.geometry.Point(xy) for xy in zip(df.X, df.Y)]
gdf = geopandas.GeoDataFrame(df, geometry=geom)
print type(gdf)

輸出爲

<class 'geopandas.geodataframe.GeoDataFrame'>

示例3. osm路網

下面這個例子,首先獲取一個城市(如青島)的空間範圍,根據這個範圍下載openstreetmap的道路數據存入geodataframe對象,而後繪製出來。

1. 獲取空間範圍

這裏用以前提到的geocoder這個工具,網友也提到這些地理編碼獲取的座標並不許確,咱們暫且先不考慮精度的問題。

import geocoder
from shapely.geometry import Polygon

g = geocoder.arcgis(u"青島")
min_lat = g.bbox.get('southwest')[0]
min_lon = g.bbox.get('southwest')[1]
max_lat = g.bbox.get('northeast')[0]
max_lon = g.bbox.get('northeast')[1]

boundary = Polygon([(min_lon, min_lat),(min_lon,max_lat),(max_lon,max_lat), (max_lon, min_lat)])

這樣獲取到的青島市的空間範圍(外接矩形)爲

{'northeast': [36.209606, 120.482939], 'southwest': [35.987606, 120.260939]}
2. 下載osm數據

這裏用到geopandas_osm這個工具,安裝命令爲

pip install git+https://github.com/jwass/geopandas_osm.git

將空間範圍的polygon對象做爲參數便可,能夠查看一下對象類型和投影參數:

import geopandas_osm.osm
df = geopandas_osm.osm.query_osm('way', boundary, recurse='down', tags='highway')

print type(df)
print df.crs

輸出爲

<class 'geopandas.geodataframe.GeoDataFrame'>
{'init': 'epsg:4326', 'no_defs': True}

直接獲取到的osm數據比較亂,作進一步篩選:

way = df[df.type == 'LineString'][['highway', 'name', 'geometry']]
way.head()

能夠計算道路的長度,這裏只是示意。直接計算length並不對,應該先投影到平面座標系。

df.ix[0].geometry.length

輸出爲

0.0014679943869086182
3. 繪製路網

能夠直接用plot命令,繪製出來:

way.plot(column="name",colormap=cm.coolwarm_r)

代碼下載

若是對本文中的代碼(.ipynb文件)感興趣,百度網盤連接:http://pan.baidu.com/s/1mh8FghE, 密碼請在關注我的微信公衆號stdrei後,輸入口令‘pandas2geo’自動獲取。

相關文章
相關標籤/搜索