開始使用免費開始

計算重心(centroid)

邊界框(bounding box)的範圍可能從一個城市街廓到整個州,甚至是國家。為了簡化處理方式,我們可以把邊界框轉換成所謂的「重心(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(____)
編輯並執行程式碼