Calcul du centroïde
La « bounding box » peut couvrir un pâté de maisons, tout un État ou même un pays. Pour simplifier le traitement, une approche consiste à convertir cette boîte en un centroïde, c’est‑à‑dire le centre de la bounding box. Le calcul du centroïde est simple : on calcule les points médians des segments formés par les latitudes et longitudes.
numpy a été importé sous le nom np.
Cet exercice fait partie du cours
<cours>Analyser des données de réseaux sociaux en Python</cours>Instructions de l’exercice
- Récupérez le premier ensemble de coordonnées depuis le JSON de place.
- Calculez la longitude centrale en additionnant la liste des longitudes puis en divisant par deux.
- Faites la même chose pour les latitudes.
- Appliquez la fonction
calculateCentroid()à la colonneplace.
Exercice interactif pratique
Essayez cet exercice en complétant ce code d’exemple.
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(____)