开始使用免费开始使用

计算质心

边界框的范围可能从一个城市街区到整个州,甚至国家。为简单起见,我们可以将边界框转换为"质心"(centroid),也就是边界框的中心点。质心的计算很直接——根据经纬度计算各边的中点。

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(____)
编辑并运行代码