首页 > 解决方案 > 循环并存储坐标

问题描述

我有一个如下所示的数据框副本:

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...

每行都有这种格式和一些坐标:

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))]

我想从每一行中提取纬度和经度,并将它们作为单独的列存储在数据框 heatmap_df 中。到目前为止我有这个,但我不擅长写循环。我的循环没有递归工作,它只打印出最后一个坐标。

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)

我正在尝试使用 Folium 制作包含所有坐标的热图。有人可以帮忙吗?谢谢

标签: pythonloopscoordinatesheatmapfolium

解决方案


Python 不知道你要做什么,它假设你想在每次迭代(heatmap_df[i][0].latitude, heatmap_df[i][0].longitude)的变量中存储元组值。point_i所以发生的事情是它每次都被覆盖。您想在外面声明一个列表,然后append将 Lat 和 Long 的 a 列表循环到它创建一个可以轻松成为 DF 的列表列表。此外,您在示例中的循环不是递归的,请检查递归

尝试这个:

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)

推荐阅读