python - CSV 到 Folium 热图
问题描述
我有一个 csv,其中包含许多不同的经纬度,格式如下所示:
39.360611,-74.431877
运行以下代码:
import csv
from folium import plugins
heatmap_map = folium.Map(location=[48, -102], zoom_start=3)
with open('geolocation.csv', "r") as f:
reader = csv.reader(f)
data = [[row[0], row[1]] for row in reader]
print(data)
hm = plugins.HeatMap(data)
heatmap_map.add_children(hm)
f.close()
heatmap_map.save("heatmap.html")
给我以下输出
[['39.360611', '-74.431877']]
Traceback (most recent call last):
File "C:\Users\dge\Anaconda3\lib\site-packages\folium\utilities.py", line 59, in validate_location
float(coord)
ValueError: could not convert string to float: '-'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".\heat.py", line 12, in <module>
hm = plugins.HeatMap(data)
File "C:\Users\dge\Anaconda3\lib\site-packages\folium\plugins\heat_map.py", line 67, in __init__
for line in data]
File "C:\Users\dge\Anaconda3\lib\site-packages\folium\plugins\heat_map.py", line 67, in <listcomp>
for line in data]
File "C:\Users\dge\Anaconda3\lib\site-packages\folium\utilities.py", line 63, in validate_location
.format(coord, type(coord)))
ValueError: Location should consist of two numerical values, but '-' of type <class 'str'> is not convertible to float.
似乎python将 - 符号识别为字符串而不是负数
解决方案
在尝试各种事情时,我发现 Pandas Dataframe 是将数据从 CSV 获取到热图的最佳方式。代码如下所示:
import folium
from folium import plugins
import pandas as pd
df = pd.DataFrame()
heatmap_map = folium.Map(location=[48, -102], zoom_start=3)
with open(r'geolocation.csv', "r") as f:
df = df.append(pd.read_csv(f),ignore_index = True)
df = df.dropna()
hm = plugins.HeatMap(df)
heatmap_map.add_child(hm)
f.close()
heatmap_map.save("heatmap.html")
请注意,dropna
由于某种原因,它总是在末尾输入一个空行,这解决了将此类信息传递给热图时会遇到的问题
推荐阅读
- docker - AIRFLOW_SCHEDULER_RUN_DURATION 设置并且调度程序在关闭时不会重新启动
- database - 我应该如何让我的数据库不断获取
- javascript - 将文本直接复制到asp.net中的剪贴板
- python - 如何从请求中删除不必要的标头?
- javascript - 按实现类型从类中的实现列表中获取对象的函数。(打字稿泛型)
- javascript - WebRTC - 通过替换空轨道添加轨道时避免重新协商
- docker - Docker 容器无法使用 FQDN 访问另一个容器
- c++ - 导致错误 #18 在 MSP430 上出现“)”的原因
- elasticsearch - elasticsearch中query_string中的转义属性是什么
- javascript - 如何根据 JSON 响应的内容在 Typescript 中创建特定类型