Search code examples
pythonloopscoordinatesheatmapfolium

Loop and store coordinates


I have a copy of a dataframe that looks like this:

heatmap_df = test['coords'].copy()
heatmap_df


0     [(Manhattanville, Manhattan, Manhattan Communi...
1     [(Mainz, Rheinland-Pfalz, 55116, Deutschland, ...
2     [(Ithaca, Ithaca Town, Tompkins County, New Yo...
3     [(Starr Hill, Charlottesville, Virginia, 22903...
4     [(Neuchâtel, District de Neuchâtel, Neuchâtel,...
5     [(Newark, Licking County, Ohio, 43055, United ...
6     [(Mae, Cass County, Minnesota, United States o...
7     [(Columbus, Franklin County, Ohio, 43210, Unit...
8     [(Canaanville, Athens County, Ohio, 45701, Uni...
9     [(Arizona, United States of America, (34.39534...
10    [(Enschede, Overijssel, Nederland, (52.2233632...
11    [(Gent, Oost-Vlaanderen, Vlaanderen, België - ...
12    [(Reno, Washoe County, Nevada, 89557, United S...
13    [(Grenoble, Isère, Auvergne-Rhône-Alpes, Franc...
14    [(Columbus, Franklin County, Ohio, 43210, Unit...

Each row has this format with some coordinates:

heatmap_df[2]
[Location(Ithaca, Ithaca Town, Tompkins County, New York, 14853, United States of America, (42.44770298533052, -76.48085858627931, 0.0)),
 Location(Chapel Hill, Orange County, North Carolina, 27515, United States of America, (35.916920469999994, -79.05664845999999, 0.0))]

I want to pull the latitude and longitudes from each row and store them as separate columns in the dataframe heatmap_df. I have this so far, but I suck at writing loops. My loop is not working recursively, it only prints out the last coordinates.

x = np.arange(start=0, stop=3, step=1)
for i in x:
    point_i = (heatmap_df[i][0].latitude, heatmap_df[i][0].longitude)
    i = i+1
point_i

(42.44770298533052, -76.48085858627931)

I am trying to make a heat map with all the coordinates using Folium. Can someone help please? Thank you


Solution

  • Python doesn't know what you are trying to do it's assuming you want to store the tuple value of (heatmap_df[i][0].latitude, heatmap_df[i][0].longitude) in the variable point_i for every iteration. So what happens is it is overwritten every time. You want to declare a list outside then loop the append a lists of the Lat and Long to it creating a List of List which can easily be a DF. Also, your loop in the example isn't recursive, Check this out for recursion

    Try this:

    x = np.arange(start=0, stop=3, step=1)
    points = []
    for i in x:
        points.append([heatmap_df[i][0].latitude, heatmap_df[i][0].longitude])
        i = i+1
    print(points)