การคำนวณ Centroid
Bounding box อาจครอบคลุมพื้นที่ตั้งแต่ระดับตึกไปจนถึงทั้งรัฐหรือทั้งประเทศ เพื่อให้จัดการข้อมูลได้ง่ายขึ้น วิธีหนึ่งคือแปลง bounding box ให้เป็น centroid หรือจุดกึ่งกลางของ bounding box การคำนวณ centroid ทำได้ตรงไปตรงมา โดยหาจุดกึ่งกลางของเส้นที่เกิดจากค่าละติจูดและลองจิจูด
numpy ถูก import มาในชื่อ np แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การวิเคราะห์ข้อมูลโซเชียลมีเดียด้วย Python
คำแนะนำการฝึกหัด
- ดึงชุดพิกัดแรกจาก JSON ของ place
- คำนวณค่าลองจิจูดกลาง โดยนำค่าในลิสต์ลองจิจูดมารวมกันแล้วหารด้วยสอง
- ทำแบบเดียวกันกับค่าละติจูด
- Apply ฟังก์ชัน
calculateCentroid()กับคอลัมน์place
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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(____)