AI/실습

120. [Python] [Pandas] 프로그래밍 실습 : 구글맵API 연동

천재단미 2025. 1. 24. 23:37
728x90
반응형

API

반응형

 

 

 

목차 ▽열기

 

# 한글 찍기
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb

%matplotlib inline

import platform

from matplotlib import font_manager, rc
plt.rcParams['axes.unicode_minus'] = False

if platform.system() == 'Darwin':|
    rc('font', family='AppleGothic')
elif platform.system() == 'Windows':
    path = "c:/Windows/Fonts/malgun.ttf"
    font_name = font_manager.FontProperties(fname=path).get_name()
    rc('font', family=font_name)
else:
    print('Unknown system... sorry~~~~')

 

 

 

문제 1.  데이터 세팅 

crime_in_Seoul.csv 파일을 pandas 로 읽어오세요.

한글이 깨지지 않도록 encoding='euc-kr' 옵션을 넣습니다.

 

 

 

풀이 1.   

df = pd.read_csv('../data/crime_in_Seoul.csv',encoding='euc-kr )

df['절도 발생'] = df['절도 발생'].str.replace(',','').astype(int)
df['절도 검거'] = df['절도 검거'].str.replace(',','').astype(int)
df['폭력 발생'] = df['폭력 발생'].str.replace(',','').astype(int)
df['폭력 검거'] = df['폭력 검거'].str.replace(',','').astype(int)



#하나씩 진행하는게 번거롭다면 thousands = ',' 

df = pd.read_csv('../data/crime_in_Seoul.csv',encoding='euc-kr', thousands = ','  )

df

스크린샷 2025-01-25 오후 1

 

 

 

코드분석

 

thousands = ','  :  천 단위 구분 기호가 포함된 문자열을 숫자로 변환

 

 

출력

: df

스크린샷 2025-01-25 오후 2

 

 

 


 

 

 

문제 2. 구글맵API 연동

경찰서들은 하나의 구에 여러개가 있을 수 있습니다. 따라서 우리는 구 단위로 데이터를 통합하겠습니다.

 

 문제 2-1. 

경찰서가 무슨 구에 있는지 확인하기 위해, 구글맵 API를 이용하겠습니다.

구글맵 API를 이용하기 위해서는 구글맵 라이브러리를 설치합니다.

아나콘다 프롬프트 실행 후, pip install googlemaps 실행

! pip install googlemaps

스크린샷 2025-01-25 오후 1

 

 

 문제 2-2.

 

구글 클라우드의 MAPS API 페이지로 이동하여, API 키를 생성합니다.

https://mapsplatform.google.com/?hl=ko

 

Google Maps Platform - Location and Mapping Solutions

Create real world and real time experiences for your customers with dynamic maps, routes & places APIs from Google Maps Platform’s location solutions.

mapsplatform.google.com

 

콘솔로 이동 => Geocoding API 선택 => 사용자인증정보 에서 API 키 생성

스크린샷 2025-01-25 오후 1

 

스크린샷 2025-01-25 오후 1
스크린샷 2025-01-24 오전 11
스크린샷 2025-01-24 오전 11
스크린샷 2025-01-25 오후 1

 

 

풀이  2. 

import googlemaps

gmaps_key = "API key" # 자신의 key를 사용합니다.
gmaps = googlemaps.Client(key=gmaps_key)

# 리스트로 만들어서 원하는 정보 컬럼을 가져온다 
result = gmaps.geocode('서울중부경찰서', language='ko')

result

 

출력

: result

스크린샷 2025-01-25 오후 1

 

 

 

 

 


 

 

 

 

문제 3.  컬럼 추가 

station_addreess 에 저장된 주소에서, 구만 따로 띄어냅니다. (예, 종로구)

따로 띄어낸 구를, crime_anal_police 에 '구별' 컬럼을 만들어서 넣습니다.

 

 

풀이 3.  

get_address('서울중부경찰서')
# '대한민국 서울특별시 중구 퇴계로 67'
get_address('서울종로경찰서')
#'대한민국 서울특별시 종로구 인사동5길 41'

result[0]['formatted_address' ]

'서울' + df_0['관서명'] + '경찰서'


def get_address(name) :
    result = gmaps.geocode(name, language='ko')
    return result[0]['formatted_address' ]
    

df_name = '서울' + df['관서명'].str[  : -2+1 ] + '경찰서'
df_name

df_0_address = df_0_name.apply(get_address)

df['구별'] = df_address.str.split().str[2]
df

스크린샷 2025-01-24 오전 11
스크린샷 2025-01-25 오후 3
스크린샷 2025-01-25 오후 3
스크린샷 2025-01-25 오후 3

 

 

코드분석

result 에서 구별을 추출할 수 있는 컬럼은 'formatted_address': '대한민국 서울특별시 중구 퇴계로 67' 입니다. 

'서울' + df_0['관서명'] + '경찰서'  < 예시  서울중부서경찰서 >

하지만 원하는 정보는 서울중서경찰서  서울중부경찰서에서 '서' 를 제외 해줘야 합니다. 

 df['관서명'].str[  : -2+1 ]  :  '중부서'에서 '중부' 만 추출하여라 

df_name = '서울' + df['관서명'].str[  : -2+1 ] + '경찰서'  < 예시  서울중부경찰서 >

df_address.str.split().str[2] : str.split()을 사용해 공백으로 나눈 뒤 적절한 인덱스 값을 참조해야 합니다.

 

 

 

출력

:  df

스크린샷 2025-01-25 오후 2

 

 

 


 

 

 

문제 3. csv 파일 저장

crime_anal_police 데이터프레임을, csv 파일로 저장합니다.

저장할 파일명은 new_crime_in_Seoul.csv 로 저장하세요. 저장하는 함수는, 데이터프레임의 to_csv 입니다.

 

 

 

풀이 3.  

df.to_csv('new_crime_in_Seoul.csv', index=False)

스크린샷 2025-01-25 오후 1

 

 

출력

스크린샷 2025-01-25 오후 2

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형
home
}