首页 > 解决方案 > Python Folium 错误:“并非所有参数都在字符串格式化期间转换”

问题描述

我正在尝试创建一个显示火山位置的网络地图。我在 Python 中使用 Folium 库,并使用 HTML 进行设计。我也在使用来自 Pandas DataFrame 的数据。但是,当我运行我的代码时,我收到以下错误:

Traceback (most recent call last):
  File "webmap.py", line 20, in <module>
    iframe = folium.IFrame(html=html % (name, name, str(elev)), width=200, height=100)
TypeError: not all arguments converted during string formatting

这是我的代码:

import folium
import pandas

data = pandas.read_csv("Volcanoes.txt")
latitudes = list(data["LAT"])
longitudes = list(data["LON"])
elevations = list(data["ELEV"])
names = list(data["NAME"])

html = """
Volcano name:<br>
<a href="https://www.google.com/search?q=%%22%%s%%22" target="_blank">%s</a><br>
Height: %s m
"""

map = folium.Map(location=[38.58, -99.09], zoom_start=6, tiles="Stamen Terrain")
fg = folium.FeatureGroup(name="My Map")

for lat, lon, elev, name in zip(latitudes, longitudes, elevations, names):
    iframe = folium.IFrame(html=html %(name, name, str(elev)), width=200, height=100)
    fg.add_child(folium.Marker(location=[lat, lon], popup=folium.Popup(iframe), icon=folium.Icon(color="green")))

map.add_child(fg)
map.save("Map1Advacned.html")

Pandas DataFrame 包含有关每个火山的信息,包括其位置(纬度和经度)、海拔和名称,我在代码的开头将其解析为 Python 数组。

有谁知道为什么会发生这个错误?任何帮助将非常感激。提前致谢!

标签: pythonhtmlpython-3.xpandasfolium

解决方案


我的补充数据是新加坡政府气象站温度数据。我已经对其进行了操作以适应您的示例

  1. 改变locationzoom参数,因为新加坡在不同的地方而且小得多;-)
  2. 您的核心问题是将字符串替换为html变量。我更喜欢 f-strings,所以把它改成了这个,它可以工作。
import folium
import pandas as pd

df = pd.DataFrame({'latitude': [1.3764, 1.256, 1.3337, 1.3135, 1.3399, 1.2799],
 'longitude': [103.8492, 103.679, 103.7768, 103.9625, 103.8878, 103.8703],
 'value': [32.3, 31.7, 32.2, 29.9, 32.1, 32.5],
 'tooltip': ['32.3 Ang Mo Kio Avenue 5 August 09, 2020 at 01:00PM',
  '31.7 Banyan Road August 09, 2020 at 01:00PM',
  '32.2 Clementi Road August 09, 2020 at 01:00PM',
  '29.9 East Coast Parkway August 09, 2020 at 01:00PM',
  '32.1 Kim Chuan Road August 09, 2020 at 01:00PM',
  '32.5 Marina Gardens Drive August 09, 2020 at 01:00PM']})

data = df.copy().rename({'latitude':"LAT",'longitude':"LON",'value':"ELEV",'tooltip':"NAME"}, axis=1)
latitudes = list(data["LAT"])
longitudes = list(data["LON"])
elevations = list(data["ELEV"])
names = list(data["NAME"])

def myhtml(name, elev):
    return f"""
    Volcano name:<br>
    <a href="https://www.google.com/search?q=%%22%{name}%%22" target="_blank">{name}</a><br>
    Height: {elev} m
    """
map = folium.Map(location=[1.34, 103.82], zoom_start=12, tiles="Stamen Terrain")
fg = folium.FeatureGroup(name="My Map")

for lat, lon, elev, name in zip(latitudes, longitudes, elevations, names):
    iframe = folium.IFrame(html=myhtml(name, elev), width=200, height=100)
    fg.add_child(folium.Marker(location=[lat, lon], popup=folium.Popup(iframe), icon=folium.Icon(color="green")))

map.add_child(fg)
map.save("Map1Advacned.html")


推荐阅读