iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 15
1
AI & Data

30天精通GIS資料分析-使用Python系列 第 15

Day15 PostGIS與Geopandas

昨天安裝完了PostGIS,
今天我們就在GeoPandas做資料讀寫,
另外QGIS對於PostGIS支援度也很高,把資料匯入後,也可以使用QGIS對資料做讀寫。

大綱:

  • 啟用
  • 資料匯入
  • 資料讀取

啟用

安裝完PostGIS,我們需要在DB中啟用
若未啟用postgis安裝完後在pgAdmin4或是psql輸入
postgres=# CREATE EXTENSION postgis;

資料匯入

為了用PostGIS匯入資料
我們使用data/Rail/Rail.shp

import geopandas as gpd

rail=gpd.read_file('data/Rail/Rail.shp',encoding='utf-8')
rail.crs = {'init' :'epsg:3826'} 
rail=rail.to_crs(epsg=4326)
rail.head()

https://ithelp.ithome.com.tw/upload/images/20181030/20107816SLrMqcJL0F.png
https://ithelp.ithome.com.tw/upload/images/20181030/20107816A9eW0TsvlS.png
在GeoPandas,可以使用sqlalchemy建立資料庫連線的instance,對資料庫IO

from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres:postgres@localhost:5432/postgres')

接著,使用to_sql這個方法,其中呢必須把geometry包成wkt element,由於一般使用geom作為PostGIS的空間屬性,這邊也一並處理

from geoalchemy2 import Geometry, WKTElement
rail['geom'] = rail['geometry'].apply(lambda x: WKTElement(x.wkt, srid=4326))
rail.drop('geometry', 1, inplace=True)


在to_sql的時候要設定連線實體、dtype(空間資料的坐標系統及幾何類型,如下:


rail.to_sql('rail', engine, if_exists='replace', index=False, schema='public',
           dtype={'geom': Geometry('LINESTRING', srid= 4326)})

如果是其他的型別如,Point或Polygon,記得要修改

資料讀取

資料進PostGIS後,可以使用QGIS瀏覽、處理資料,有時需要編輯幾何資料的時候,使用QGIS很方便,熟悉QGIS的邦友可以使用DB Manager對PostGIS做操作
https://ithelp.ithome.com.tw/upload/images/20181030/20107816kzOS2GxW7Z.png
https://ithelp.ithome.com.tw/upload/images/20181030/20107816Jna9KThbm8.png

https://ithelp.ithome.com.tw/upload/images/20181030/20107816c2Kdm92utv.png

而剛剛的資料也可以在讀回Geopandas

sql='select * from public.rail '
df = gpd.GeoDataFrame.from_postgis(sql, engine, geom_col='geom' )
df

https://ithelp.ithome.com.tw/upload/images/20181030/201078168t7lrmhqJZ.png
使用資料庫是資料處理及資料分析不可或缺的一環,在空間資料庫中,PostGIS非常方便,建議大家使用!


上一篇
Day14 PostGIS的安裝
下一篇
Day16 WKT與PostGIS的運算
系列文
30天精通GIS資料分析-使用Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言