selenium, shape file을 활용한 미세먼지 시각화(folium 사용)
python2019. 5. 9. 04:56
좌표계 변환 및 다시 불러오기¶
In [1]:
import shapefile
from json import dumps
import geopandas as gpd
#좌표계 변환
sf=gpd.read_file('/home/ducj/data/ducj/files/json/shp/CTPRVN_201703/TL_SCCO_CTPRVN.shp',encoding='cp949')
sf=sf.to_crs(epsg='4326')
sf.to_file('/home/ducj/data/ducj/files/json/shp/CTPRVN_201703/test.shp',encoding='cp949')
#변환 후 불러오기
reader = shapefile.Reader('/home/ducj/data/ducj/files/json/shp/CTPRVN_201703/test.shp',encoding='cp949')
In [2]:
#shape file 을 json 파일로 변환하기 위한 코드
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
atr = dict(zip(field_names, sr.record))
geom = sr.shape.__geo_interface__
name=sr.record[2]
buffer.append(dict(type="Feature", \
properties=atr,id=name,geometry=geom))
#json파일로 저장
from json import dumps
geojson = open("/home/ducj/data/ducj/files/json/shp/CTPRVN_201703/pyshp-demo.json", "w")
geojson.write(dumps({"type": "FeatureCollection",\
"features": buffer}, indent=2) + "\n")
geojson.close()
미세먼지 자료 크롤링을 위한 코드¶
In [4]:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from time import sleep
import pandas as pd
# create a new chrome session
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
driver = webdriver.Chrome(chrome_options=options, executable_path="/home/ducj/crawling/chromedriver")
driver.implicitly_wait(3)
driver.maximize_window()
url='https://www.airkorea.or.kr/web/sidoQualityCompare?itemCode=10007&pMENU_NO=101'
driver.get(url)
sleep(0.3)
html = driver.page_source
dfs = pd.read_html(html)
driver.close()
In [6]:
dfs[0]
Out[6]:
크롤링으로 생성#54620; 데이터를 필요한 형태로 변환¶
In [7]:
#데이터 생성
data=pd.DataFrame([dfs[0].transpose()[1::][0].index,dfs[0].transpose()[1::][0]]).transpose()
data=pd.DataFrame({'area':data[0],'dust':data[1]})
#데이터 수치로 변환
data['dust']=data['dust'].astype(float)
data.reset_index(inplace=True,drop=True)
data=data.set_index('area')
print(data.dtypes)
data.head()
Out[7]:
앞에서 생성한 json 파일 불러와 지역이름을 동일하게 변환¶
In [9]:
import folium
import json
json = json.load(open("/home/ducj/data/ducj/files/json/shp/CTPRVN_201703/pyshp-demo.json", encoding='utf-8'))
for i in range(17):
json['features'][i]['id']=data['dust'].index[i]
In [184]:
# for i in range(17):
# json['features'][i]['properties']['CTP_KOR_NM']=data['dust'].index[i]
지도형식으로 시각화¶
In [ ]:
map=folium.Map(location=[37.5502, 126.982], tiles='Stamen toner') # 서울시
folium.Choropleth(
geo_data=json,
name='choropleth',
data=data['dust'],
key_on='feature.id',
fill_color='YlGn',
fill_opacity=0.7,
line_opacity=0.2).add_to(map)
folium.LayerControl().add_to(map)
map.save('/home/ducj/nas/data.html')
'python' 카테고리의 다른 글
matplotlib 정리(1) (0) | 2020.02.16 |
---|---|
주피터 노트북에 메모리 사용량 모니터링 하기 (0) | 2020.01.24 |
python 회귀분석 할 때 주로 사용할 것 같은 패키지 및 코드 (0) | 2020.01.14 |
power shell 을 활용하여 windows에 jupyter notebook 설치하기 (0) | 2019.06.27 |
파이썬3.7 지뢰찾기 (0) | 2019.04.08 |