Data_Mining_Kaggle

code
data_mining
jupyter
kaggle
Author

Seongtaek

Published

May 2, 2023

Exercise 5 - Proximity Analysis

Jupyter에서 실행하기

This notebook is an exercise in the Geospatial Analysis course. You can reference the tutorial at this link.


1 Introduction

You are part of a crisis response team, and you want to identify how hospitals have been responding to crash collisions in New York City.


Before you get started, run the code cell below to set everything up.

여러분은 위기 대응 팀의 일원이며, 뉴욕시에서 발생한 충돌 사고에 대해 병원이 어떻게 대응해 왔는지를 파악하려고 합니다. 시작하기 전에 아래의 코드 셀을 실행하여 모든 설정을 수행합니다.

import math
import geopandas as gpd
import pandas as pd
from shapely.geometry import MultiPolygon

import folium
from folium import Choropleth, Marker
from folium.plugins import HeatMap, MarkerCluster

embed_map() 함수를 사용하여 지도를 시각화합니다.

def embed_map(m, file_name):
    from IPython.display import IFrame
    m.save(file_name)
    return IFrame(file_name, width='100%', height='500px')

2 Exercises

2.1 1) 충돌 데이터를 시각화합니다.

아래 코드 셀을 실행하여 2013-2018년 주요 자동차 충돌을 추적하는 GeoDataFrame 충돌을 로드합니다.

collisions = gpd.read_file("C:/Users\seong taek/Desktop/archive/NYPD_Motor_Vehicle_Collisions/NYPD_Motor_Vehicle_Collisions/NYPD_Motor_Vehicle_Collisions.shp")
collisions.head()
DATE TIME BOROUGH ZIP CODE LATITUDE LONGITUDE LOCATION ON STREET CROSS STRE OFF STREET CONTRIBU_2 CONTRIBU_3 CONTRIBU_4 UNIQUE KEY VEHICLE TY VEHICLE _1 VEHICLE _2 VEHICLE _3 VEHICLE _4 geometry
0 07/30/2019 0:00 BRONX 10464 40.841100 -73.784960 (40.8411, -73.78496) NaN NaN 121 PILOT STREET Unspecified NaN NaN 4180045 Sedan Station Wagon/Sport Utility Vehicle Station Wagon/Sport Utility Vehicle NaN NaN POINT (1043750.211 245785.815)
1 07/30/2019 0:10 QUEENS 11423 40.710827 -73.770660 (40.710827, -73.77066) JAMAICA AVENUE 188 STREET NaN NaN NaN NaN 4180007 Sedan Sedan NaN NaN NaN POINT (1047831.185 198333.171)
2 07/30/2019 0:25 NaN NaN 40.880318 -73.841286 (40.880318, -73.841286) BOSTON ROAD NaN NaN NaN NaN NaN 4179575 Sedan Station Wagon/Sport Utility Vehicle NaN NaN NaN POINT (1028139.293 260041.178)
3 07/30/2019 0:35 MANHATTAN 10036 40.756744 -73.984590 (40.756744, -73.98459) NaN NaN 155 WEST 44 STREET NaN NaN NaN 4179544 Box Truck Station Wagon/Sport Utility Vehicle NaN NaN NaN POINT (988519.261 214979.320)
4 07/30/2019 10:00 BROOKLYN 11223 40.600090 -73.965910 (40.60009, -73.96591) AVENUE T OCEAN PARKWAY NaN NaN NaN NaN 4180660 Station Wagon/Sport Utility Vehicle Bike NaN NaN NaN POINT (993716.669 157907.212)

5 rows × 30 columns

충돌 데이터를 시각화하기 위해 대화형 맵을 만들려면 “LATITUITUITY” 및 “LONGITUITY” 열을 사용합니다. 어떤 종류의 지도가 가장 효과적이라고 생각합니까?

m_1 = folium.Map(location=[40.7, -74], zoom_start=11) 

# Your code here: Visualize the collision data
HeatMap(data=collisions[['LATITUDE', 'LONGITUDE']], radius=9).add_to(m_1)

# Show the map
embed_map(m_1, "q_1.html")
m_1
Make this Notebook Trusted to load map: File -> Trust Notebook

2.2 2) 병원 범위를 이해합니다.

다음 코드 셀을 실행하여 병원 데이터를 로드합니다.

hospitals = gpd.read_file("C:/Users\seong taek/Desktop/archive/nyu_2451_34494/nyu_2451_34494/nyu_2451_34494.shp")
hospitals.head()
id name address zip factype facname capacity capname bcode xcoord ycoord latitude longitude geometry
0 317000001H1178 BRONX-LEBANON HOSPITAL CENTER - CONCOURSE DIVI… 1650 Grand Concourse 10457 3102 Hospital 415 Beds 36005 1008872.0 246596.0 40.843490 -73.911010 POINT (1008872.000 246596.000)
1 317000001H1164 BRONX-LEBANON HOSPITAL CENTER - FULTON DIVISION 1276 Fulton Ave 10456 3102 Hospital 164 Beds 36005 1011044.0 242204.0 40.831429 -73.903178 POINT (1011044.000 242204.000)
2 317000011H1175 CALVARY HOSPITAL INC 1740-70 Eastchester Rd 10461 3102 Hospital 225 Beds 36005 1027505.0 248287.0 40.848060 -73.843656 POINT (1027505.000 248287.000)
3 317000002H1165 JACOBI MEDICAL CENTER 1400 Pelham Pkwy 10461 3102 Hospital 457 Beds 36005 1027042.0 251065.0 40.855687 -73.845311 POINT (1027042.000 251065.000)
4 317000008H1172 LINCOLN MEDICAL & MENTAL HEALTH CENTER 234 E 149 St 10451 3102 Hospital 362 Beds 36005 1005154.0 236853.0 40.816758 -73.924478 POINT (1005154.000 236853.000)

“위도” 및 “경도” 열을 사용하여 병원 위치를 시각화합니다.

m_2 = folium.Map(location=[40.7, -74], zoom_start=11) 

# Your code here: Visualize the hospital locations
for idx, row in hospitals.iterrows():
    Marker([row['latitude'], row['longitude']], popup=row['name']).add_to(m_2)

# Show the map
embed_map(m_2, "q_2.html")
m_2
Make this Notebook Trusted to load map: File -> Trust Notebook

2.3 3) 가장 가까운 병원이 10킬로미터 이상 떨어진 때는 언제였습니까?

가장 가까운 병원에서 10km 이상 떨어진 곳에서 발생한 충돌로 인한 모든 행을 포함하는 DataFrame outside_range를 만듭니다.

병원과 충돌은 모두 EPSG 2263을 좌표계로 사용하고 EPSG 2263은 미터 단위를 사용합니다.

# Your code here
coverage = gpd.GeoDataFrame(geometry=hospitals.geometry).buffer(10000)
my_union = coverage.geometry.unary_union
outside_range = collisions.loc[~collisions["geometry"].apply(lambda x: my_union.contains(x))]

다음 코드 셀은 가장 가까운 병원에서 10킬로미터 이상 떨어진 곳에서 발생한 충돌의 비율을 계산합니다.

percentage = round(100*len(outside_range)/len(collisions), 2)
print("Percentage of collisions more than 10 km away from the closest hospital: {}%".format(percentage))
Percentage of collisions more than 10 km away from the closest hospital: 15.12%

2.4 4) 추천자를 만들어 보세요.

먼 곳에서 충돌이 발생할 경우 부상자를 가장 가까운 병원으로 이송하는 것이 더욱 중요합니다.

이를 고려하여 다음과 같은 추천인을 생성하기로 결정합니다:

  • 충돌 위치(EPSG 2263)를 입력으로 사용합니다,
  • 가장 가까운 병원을 찾습니다(EPSG 2263에서 거리 계산이 수행되는 곳)
  • 가장 가까운 병원의 이름을 반환합니다.
def best_hospital(collision_location):
    # Your code here
    idx_min = hospitals.geometry.distance(collision_location).idxmin()
    my_hospital = hospitals.iloc[idx_min]
    name = my_hospital["name"]
    return name
# Test your function: this should suggest CALVARY HOSPITAL INC
print(best_hospital(outside_range.geometry.iloc[0]))
CALVARY HOSPITAL INC

2.5 5) 가장 수요가 많은 병원은 어디입니까?

Outside_range DataFrame에서 충돌만 고려할 때 가장 권장되는 병원은 무엇입니까?

4)에서 생성한 함수가 반환한 병원 이름과 정확히 일치하는 파이썬 문자열이어야 합니다.

# Your code here
highest_demand = outside_range.geometry.apply(best_hospital).value_counts().idxmax()
highest_demand
'JAMAICA HOSPITAL MEDICAL CENTER'

2.6 6) 서울시는 어디에 새로운 병원을 지어야 합니까?

가장 가까운 병원에서 10km 이상 떨어진 곳에서 발생한 충돌 외에도 병원 위치를 시각화하려면 다음 코드 셀을 (변경 없이) 실행합니다.

m_6 = folium.Map(location=[40.7, -74], zoom_start=11) 

coverage = gpd.GeoDataFrame(geometry=hospitals.geometry).buffer(10000)
folium.GeoJson(coverage.geometry.to_crs(epsg=4326)).add_to(m_6)
HeatMap(data=outside_range[['LATITUDE', 'LONGITUDE']], radius=9).add_to(m_6)
folium.LatLngPopup().add_to(m_6)

embed_map(m_6, 'm_6.html')
m_6
Make this Notebook Trusted to load map: File -> Trust Notebook

지도의 아무 곳이나 클릭하면 위도와 경도의 해당 위치가 있는 팝업이 나타납니다.

뉴욕시는 두 개의 새로운 병원의 위치를 결정하는 데 도움을 요청합니다. 그들은 특히 3) 단계에서 계산된 백분율을 10% 미만으로 만들기 위해 위치를 식별하는 데 도움을 받기를 원합니다. 지도를 사용하여(그리고 구역법이나 병원을 짓기 위해 어떤 잠재적인 건물을 제거해야 할지에 대한 걱정 없이), 도시가 이 목표를 달성하는 데 도움이 될 두 곳을 식별할 수 있습니까?

병원 1에 대해 제안된 위도와 경도를 각각 ’lat_1’과 ’long_1’에 입력합니다. (병원 2도 마찬가지입니다.)

그런 다음 새 병원의 효과를 확인하기 위해 나머지 셀을 그대로 실행합니다. 만약 두 개의 새로운 병원이 그 비율을 10% 미만으로 만든다면, 당신의 대답은 정확하다고 표시될 것입니다.

# Your answer here: proposed location of hospital 1
lat_1 = 37
long_1 = 126

# Your answer here: proposed location of hospital 2
lat_2 = 37
long_2 = 126


# Do not modify the code below this line
try:
    new_df = pd.DataFrame(
        {'Latitude': [lat_1, lat_2],
         'Longitude': [long_1, long_2]})
    new_gdf = gpd.GeoDataFrame(new_df, geometry=gpd.points_from_xy(new_df.Longitude, new_df.Latitude))
    new_gdf.crs = {'init' :'epsg:4326'}
    new_gdf = new_gdf.to_crs(epsg=2263)
    # get new percentage
    new_coverage = gpd.GeoDataFrame(geometry=new_gdf.geometry).buffer(10000)
    new_my_union = new_coverage.geometry.unary_union
    new_outside_range = outside_range.loc[~outside_range["geometry"].apply(lambda x: new_my_union.contains(x))]
    new_percentage = round(100*len(new_outside_range)/len(collisions), 2)
    print("(NEW) Percentage of collisions more than 10 km away from the closest hospital: {}%".format(new_percentage))

    # make the map
    m = folium.Map(location=[40.7, -74], zoom_start=11) 
    folium.GeoJson(coverage.geometry.to_crs(epsg=4326)).add_to(m)
    folium.GeoJson(new_coverage.geometry.to_crs(epsg=4326)).add_to(m)
    for idx, row in new_gdf.iterrows():
        Marker([row['Latitude'], row['Longitude']]).add_to(m)
    HeatMap(data=new_outside_range[['LATITUDE', 'LONGITUDE']], radius=9).add_to(m)
    folium.LatLngPopup().add_to(m)
    display(embed_map(m, 'q_6.html'))
except:
    q_6.hint()

m
C:\Users\seong taek\anaconda3\lib\site-packages\pyproj\crs\crs.py:141: FutureWarning: '+init=<authority>:<code>' syntax is deprecated. '<authority>:<code>' is the preferred initialization method. When making the change, be mindful of axis order changes: https://pyproj4.github.io/pyproj/stable/gotchas.html#axis-order-changes-in-proj-6
  in_crs_string = _prepare_from_proj_string(in_crs_string)


(NEW) Percentage of collisions more than 10 km away from the closest hospital: 15.12%
Make this Notebook Trusted to load map: File -> Trust Notebook

3 Congratulations!

You have just completed the Geospatial Analysis micro-course! Great job!


Have questions or comments? Visit the course discussion forum to chat with other learners.