import googlemaps
gmaps_key = 'AIzaSyBnjsDKM8TGvUV97-U1WnnagJ_vO4DPjHE'
gmaps = googlemaps.Client(key=gmaps_key)
# 예시
gmaps.geocode('서울영등포경찰서', language='ko')
tmp[0].get('geometry')["location"] #geometry의 key에 해당하는 value 반환 후 location의 kiey에 해당하는 value 반환(dict type 이기에)
tmp[0].get('geometry').get("location") #dict.get('key') = dict['key']
print(tmp[0].get('geometry').get("location")['lat']) #위도 출력
print(tmp[0].get('geometry').get("location")['lng']) #경도 출력
tmp[0].get('formatted_address') # 전체 주소 출력
tmp[0].get('formatted_address').split() # 띄어쓰기 형태로 구분하여 list에 담아줌
tmp[0].get('formatted_address').split()[2] # 세번째 아이템 출력(경찰서가 위치한 구)
crime_station["구별"] = np.nan
crime_station['lat'] = np.nan
crime_station["lng"] = np.nan
crime_station
for idx, rows in crime_station.iterrows():
print(idx)
tmp[0].get('formatted_address')
count = 0
for idx, rows in crime_station.iterrows():
if str(idx) != '종암' :
station_name = '서울' + str(idx) + '경찰서'
tmp = gmaps.geocode(station_name, language='ko')
tmp_gu = tmp[0].get('formatted_address').split()[2]
lat = tmp[0].get('geometry').get("location")['lat']
lng = tmp[0].get('geometry').get("location")['lng']
# 데이터 프레임의 NaN을 채워줄 data 확보
crime_station.loc[idx, "lat"] = lat #loc 함수는 '인덱스명'으로 인수를 받음(iloc는 인덱스 번호)
crime_station.loc[idx, "lng"] = lng
crime_station.loc[idx, "구별"] = tmp_gu
else :
continue
print(count)
count += 1
위치한 구, 위도, 경도가 추가된 데이터프레임
여러 레벨로 나뉘어진 컬럼명 확인
crime_station.columns.get_level_values(0) #0번째 행
# 컬럼 합치기
tmp = [
crime_station.columns.get_level_values(0)[n] + crime_station.columns.get_level_values(1)[n]
for n in range(0, len(crime_station.columns.get_level_values(0)))
]
tmp # 새로 넣을 컬럼명
crime_station.columns = tmp
crime_station.to_csv("../data/02. crime_in_Seoul_raw.csv", sep=',', encoding='utf-8')