Create PolyLines though a loop in Folium / Pandas

41 views Asked by At

I try to create multiple lines from a Dataframe in JupyterLab while looping. I have created the following code but every time I try to run it, my Jupyter Notebook crashes and tell me that the Kernel has died. What am I missing here?

m = folium.Map(location=[VstBreitengrad, VstLängengrad], max_zoom=20, zoom_start=5)

for index, row in dfFilter.iterrows():

    Breitengrad = row["Breitengrad_x"]
    Längengrad = row["Längengrad_x"]

    coordinates = [
                [Breitengrad, Längengrad],
                [20, 20]
    ]
               
    folium.PolyLine(
            locations=coordinates,
            color="#FF0000",
            weight=5,
    ).add_to(m)

m

Breitengrad_x and Längengrad_x are the columns in the dataframe from where I'll get the coordinates. If I hardcode the coordinates like

Breitengrad = 50 #row["Breitengrad_x"]
Längengrad = 20 #row["Längengrad_x"]

the code runs without a problem. Thanks a lot for your ideas / solutions.

2

There are 2 answers

1
e-motta On BEST ANSWER

Assuming the dtype of Breitengrad_x is int64, row["Breitengrad_x"] will give you a value of type numpy.int64. That's what may be causing the problem, since your code runs with the hardcoded values.

Tox fix it, try converting the values into regular int:

    ...
    Breitengrad = int(row["Breitengrad_x"])
    Längengrad = int(row["Längengrad_x"])
    ...
0
Timeless On

FWIW, iterating through pandas objects is generally slow (see here).

I would suggest you to make a GeoDataFrame using LineString objects, then explore them to make a folium Map :

gdf = gpd.GeoDataFrame(
    geometry=[
        LineString([extremity, ORIGIN])
        for extremity in dfFilter.to_numpy()[:, ::-1]
        # or hardcoded : dfFilter[["Längengrad_x", "Breitengrad_x"]].to_numpy()
    ],
    crs=4326,
)

m = gdf.explore(
    style_kwds={
        "weight": 5, "color": "#FF0000",
    },
    width=700, height=350,
)

Output (m):

enter image description here

Used input (dfFilter):

from shapely import LineString
import geopandas as gpd

ORIGIN = (20, 20) # lon/lat

dfFilter = pd.DataFrame(
    {
        "Breitengrad_x": [50, 39, 10, 9],
        "Längengrad_x": [20, -2, 3.5, 38],
    }
)