graphPaname/app/preprocessing.py

39 lines
1.2 KiB
Python

from folium import Map, Marker, PolyLine
from pandas import DataFrame, json_normalize
from app.data_request import request_dataset
from constants import COLUMNS, COORDINATES
def create_dataframe(dataset) -> DataFrame:
"""
Creates a DataFrame from a JSON response
"""
json = request_dataset(dataset)
df = json_normalize(data=json, record_path=["records"], errors="ignore",)
filtered_df = df.filter(items=COLUMNS[dataset])
return filtered_df
def reverse_coordinates(row):
"""
Reverses each tuples coordinates to ensure folium can parse them correctly
"""
coord = [tuple(reversed(t)) for t in row["fields.geo_shape.coordinates"]]
return coord
def create_map(df):
"""
Creates a Map with markers or lines from the DataFrame
"""
m = Map(location=COORDINATES, zoom_start=12, tiles="Stamen Terrain")
for index, row in df.iterrows():
if row["fields.geo_shape.type"] == "LineString":
coord = reverse_coordinates(row["fields.geo_shape.coordinates"])
PolyLine(locations=coord, color="blue", opacity=0.5).add_to(m)
else:
lng, lat = row["fields.geo_shape.coordinates"]
Marker(location=[lat, lng]).add_to(m)
m.save("app/templates/map.html")