본문 바로가기
GIS Tech/GIS Data Process

Python (GIS+General) Tip 모음

by mpv 2021. 1. 11.

1. GIS 파일 (SHP, PRJ) 로드하는법 (fiona, geopandas)

기본적으로 geopandas의 read_file을 하면 데이터를 로드하지만, prj파일을 놓쳐서 일일히 설정해 줘야 할 때가 있다. 이럴 때

import fiona
import geopandas as gpd
c = fiona.open('SeoulTrafficData/NODELINKDATA-2020-03-31/MOCT_LINK.shp', encoding='euc-kr')
link_gdf = gpd.GeoDataFrame.from_features(c, crs=c.crs).to_crs('epsg:4326')

이와 같이 fiona 라이브러리를 활용하면 자동으로 prj 파일도 함께 읽어 좌표계를 설정하여준다.

 

2. pd.df → gpd.gdf 바꾸는 방법

gdf = gpd.GeoDataFrame(
    df, geometry=gpd.points_from_xy(x=df.lng, y=df.lat)
)
gdf.crs = 'EPSG:4326'

 

3. 영역 geojson 범위내 gpd query하는 방법

from shapely.geometry import Point, Polygon

yunnam_large = {'type': 'Polygon',
 'coordinates': [[[126.92572992898702, 37.55835818322421],
   [126.92616538295539, 37.55864227038824],
   [126.92658623986753, 37.55938810776263],
   [126.92677406036564, 37.56118120785994],
   [126.9282886257802, 37.56334452890169],
   [126.92638553613328, 37.56494713073428],
   [126.9243245551222, 37.565900883346934],
   [126.9196036221869, 37.5667807387447],
   [126.91729357199945, 37.56765310878508],
   [126.91688686271446, 37.566950046607175],
   [126.911545990937, 37.56548655281125],
   [126.91632828606713, 37.56035436030137],
   [126.91882134961368, 37.55750895062923],
   [126.92156261652076, 37.555222270447274],
   [126.92572992898702, 37.55835818322421]]]}
   
gg = Polygon(yunnam_large['coordinates'][0])
gdf = gdf[gdf.geometry.within(gg)]

 

4. python matplotlib.pyplot legend 위치 오른쪽으로

plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

 

참조: stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot

 

How to put the legend out of the plot

I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure...

stackoverflow.com

 

5. matplotlib 한글입력

plt.rcParams["font.family"] = 'nanumgothic'
plt.rcParams['axes.unicode_minus'] = False

 

6. Proj Transformer 좌표변환

from pyproj import Proj, transform

inProj = Proj('+proj=tmerc +lat_0=38 +lon_0=127.0028902777778 +k=1 +x_0=200000 +y_0=500000 +ellps=bessel +units=m +no_defs +towgs84=-115.80,474.99,674.11,1.16,-2.31,-1.63,6.43')
outProj = Proj(init='epsg:4326')
x1,y1 = yldf.iloc[0].x, yldf.iloc[0].y
x2,y2 = transform(inProj,outProj,x1,y1)
print (y2,',',x2)

 

간단하게는 이렇게 바꾸거나

from pyproj import Transformer
transformer = Transformer.from_proj(inProj, outProj)
points = []
for index, item in yldf[['x', 'y']].iterrows():
    #x1,y1 = item.x, item.y
    points.append((item.x, item.y))
    
latlist, lnglist = [], []
for pt in transformer.itransform(points):
    latlist.append(pt[1])
    lnglist.append(pt[0])
    
yldf['lat'] = latlist
yldf['lng'] = lnglist

이런식으로 위도 경도를 한꺼번에 변환 가능하다.

 

7. Dictionary 값으로 정렬

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

 

댓글