始める無料で始める

セントロイドの計算

バウンディングボックスは、1つの街区から州全体、さらには国全体にまで及ぶことがあります。こうしたデータを簡単に扱う方法のひとつが、バウンディングボックスをセントロイド(バウンディングボックスの中心点)に変換することです。セントロイドの計算はシンプルで、緯度と経度がつくる線分の中点を求めるだけです。

numpy は np としてインポート済みです。

この演習はコースの一部です

Python でのソーシャルメディアデータ分析

コースを見る

演習の手順

  • place の JSON から最初の座標セットを取得します。
  • 経度のリストを合計して2で割ることで、中心となる経度を計算します。
  • 緯度についても同様に計算します。
  • 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(____)
コードを編集して実行