TOP
class="layout-aside-left paging-number">
본문 바로가기
데이터분석 만능열쇠 [파이썬]/<파이썬 데이터 분석>

[파이썬] 주유소 가격 비교하기 - 4

by 기록자_Recordian 2024. 4. 29.
728x90
반응형
시작에 앞서
해당 내용은 <파이썬으로 데이터 주무르기> -민형기 저, BJPUBLIC 출판사 의 내용을 토대로 작성되었습니다.
보다 자세한 내용은 해당 교재를 확인하여 주시기 바랍니다.

기존 작업 내용

 

 

[파이썬] 주유소 가격 비교하기 - 3

시작에 앞서해당 내용은 -민형기 저, BJPUBLIC 출판사 의 내용을 토대로 작성되었습니다.<span style="font-family:..

puppy-foot-it.tistory.com


서울시 주유 가격 상하위 10개 주유소 각각 저장 하기

 

주유 가격 상위 10개 주유소를 oil_price_top10 이름으로 저장하기

oil_price_top10 = station.sort_values(by='가격', ascending=False).head(10)
oil_price_top10

주유 가격 상위 10개

 

주유 가격 하위 10개 주유소를 oil_price_bottom10 이름으로 저장하기

oil_price_bottom10 = station.sort_values(by='가격', ascending=True).head(10)
oil_price_bottom10

주유 가격 하위 10개

주유소 가격 상하위 10개 업체 위도, 경도 정보 읽어오기

 

Google Maps API Key 입력

gmaps_key = "본인의 API Key"
gmaps = googlemaps.Client(key=gmaps_key)

 

주유소 가격 상위 10개 주유소에 대해 위도, 경도 정보 읽어오기

※ 혹시 알 수 없는 문제로 에러가 나는 것에 대비하기 위하여 try-except 구문 사용

(try 구문을 실행하다가 에러가 나면 except 구문에서 지정된 코드를 실행 - 이 구문에서는 NaN 저장하도록 함)

from tqdm import tqdm_notebook

lat = []
lng = []

for n in tqdm_notebook(oil_price_top10.index):
    try:
        tmp_add = str(oil_price_top10['주소'][n]).split('(')[0]
        tmp_map = gmaps.geocode(tmp_add)
        
        tmp_loc = tmp_map[0].get('geometry')
        lat.append(tmp_loc['location']['lat'])
        lng.append(tmp_loc['location']['lng'])

    except:
        lat.append(np.nan)
        lng.append(np.nan)
        print("Here is nan!")

oil_price_top10['lat'] = lat
oil_price_top10['lng'] = lng
oil_price_top10

 

주유소 가격 상위 10개 업체 위도, 경도

 

마찬가지로, 하위 가격 10개 업체의 경도, 위도 정보도 읽어온다

lat = []
lng = []

for n in tqdm_notebook(oil_price_bottom10.index):
    try:
        tmp_add = str(oil_price_bottom10['주소'][n]).split('(')[0]
        tmp_map = gmaps.geocode(tmp_add)
        
        tmp_loc = tmp_map[0].get('geometry')
        lat.append(tmp_loc['location']['lat'])
        lng.append(tmp_loc['location']['lng'])

    except:
        lat.append(np.nan)
        lng.append(np.nan)
        print("Here is nan!")

oil_price_bottom10['lat'] = lat
oil_price_bottom10['lng'] = lng
oil_price_bottom10

주유 가격 하위 10개 업체의 위도, 경도 포함 리스트

 

앞서 위도, 경도 읽어올 때 사용했던 에러가 나면 NaN으로 처리한 것에 대해 notnull 명령을 이용해서 NaN이 아닐때만 지도에 표기하도록 한다

※ 들여쓰기가 맞지 않으면 오류가 나니 주의!

map = folium.Map(location=[37.5202, 126.975], zoom_start=10.5)

for n in oil_price_top10.index:
    if pd.notnull(oil_price_top10['lat'][n]):
        folium.CircleMarker([oil_price_top10['lat'][n], oil_price_top10['lng'][n]],
                             radius=15, color='#CD3181', fill_color='#CD3181').add_to(map)
        
    for n in oil_price_bottom10.index:
        if pd.notnull(oil_price_bottom10['lat'][n]):
            folium.CircleMarker([oil_price_bottom10['lat'][n], oil_price_bottom10['lng'][n]],
                             radius=15, color='#CD3186cc', fill_color='#CD3186cc').add_to(map)

map

 

주유소 상하위 10개 업체 circleMarker 입력
주유 가격 상하위 10개 업체 지도에 표기하기

 

728x90
반응형