使用结构化查询在使用GeoPy的数据帧中对记录进行地理编码

2024-05-14 06:05:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用结构化查询在GeoPy中进行地理编码,我想在大量观测数据上运行此功能。我不知道如何使用pandas数据帧(或者可以轻松转换为pandas数据帧或从pandas数据帧转换为pandas数据帧)执行这些查询

首先,一些机构:

from geopy.extra.rate_limiter import RateLimiter
from geopy.geocoders import Nominatim
Ngeolocator = Nominatim(user_agent="myGeocoder")
Ngeocode = RateLimiter(Ngeolocator.geocode, min_delay_seconds=1)

df = pandas.DataFrame(["Bob", "Joe", "Ed"])
df["CLEANtown"] = ['Harmony', 'Fargo', '']
df["CLEANcounty"] = ['', '', 'Traill']
df["CLEANstate"] = ['Minnesota', 'North Dakota', 'North Dakota']
df["full"]=['Harmony, Minnesota','Fargo, North Dakota','Traill County, North Dakota']
df.columns = ["name"] + list(df.columns[1:])

我知道如何通过提供字典在单个位置上运行结构化查询。即:

q={'city':'Harmony', 'county':'', 'state':'Minnesota'}
testN=Ngeocode(q,addressdetails=True)

我知道如何从数据框中简单地使用一列字符串进行地理编码。即:

df['easycode'] = df['full'].apply(lambda x: Ngeocode(x, language='en',addressdetails=True).raw)

但是如何将CLEANtown、CLEANcounty和CLEANstate列逐行转换为字典,将这些字典用作结构化查询,并将结果放回pandas数据框架

谢谢大家!


Tags: 数据fromimportpandas编码df字典地理
1条回答
网友
1楼 · 发布于 2024-05-14 06:05:34

一种方法是使用数据帧的apply方法而不是序列。这将把整排传递给lambda。例如:

df["easycode"] = df.apply(
    lambda row: Ngeocode(
        {
            "city": row["CLEANtown"],
            "county": row["CLEANcounty"],
            "state": row["CLEANstate"],
        },
        language="en",
        addressdetails=True,
    ).raw,
    axis=1,
)

类似地,若您想先制作一行词典,可以执行以下操作:

df["full"] = df.apply(
    lambda row: {
        "city": row["CLEANtown"],
        "county": row["CLEANcounty"],
        "state": row["CLEANstate"],
    },
    axis=1,
)
df["easycode"] = df["full"].apply(
    lambda x: Ngeocode(
        x,
        language="en",
        addressdetails=True,
    ).raw
)

相关问题 更多 >