중심점 계산하기
바운딩 박스는 한 블록부터 주 전체, 심지어 국가 단위까지 범위가 매우 다양해질 수 있어요. 단순화를 위해 바운딩 박스를 그 중심을 나타내는 centroid(중심점)로 변환하는 방법을 사용할 수 있습니다. 중심점 계산은 간단해요. 위도와 경도로 만들어지는 변의 중점을 계산하면 됩니다.
numpy는 np로 임포트되어 있어요.
이 연습은 강의의 일부입니다
Python으로 소셜 미디어 데이터 분석하기
연습 안내
- place JSON에서 첫 번째 좌표 집합을 가져오세요.
- 경도 리스트를 모두 더한 뒤 2로 나눠 중앙 경도를 계산하세요.
- 위도도 같은 방식으로 계산하세요.
place열에calculateCentroid()함수를 적용하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
def calculateCentroid(place):
""" Calculates the centroid from a bounding box."""
# Obtain the coordinates from the bounding box.
coordinates = place[____][____][0]
longs = np.unique( [x[0] for x in coordinates] )
lats = np.unique( [x[1] for x in coordinates] )
if len(longs) == 1 and len(lats) == 1:
# return a single coordinate
return (longs[0], lats[0])
elif len(longs) == 2 and len(lats) == 2:
# If we have two longs and lats, we have a box.
central_long = ____.____(____) / ____
central_lat = ____.____(____) / ____
else:
raise ValueError("Non-rectangular polygon not supported: %s" %
",".join(map(lambda x: str(x), coordinates)) )
return (central_long, central_lat)
# Calculate the centroids of place
centroids = tweets_sotu[____].apply(____)