如何从经纬度坐标列表中获取城市、州和国家?

How to get city, state, and country from a list of latitude and longitude coordinates?

我有 500,000 个经纬度坐标列表,如下所示:

Latitude   Longitude  
42.022506  -88.168156  
41.877445  -87.723846  
29.986801  -90.166314  

我希望使用 python 获取新列中每个坐标的城市、州和国家/地区,如下所示:

Latitude   Longitude   City        State   Country
42.022506  -88.168156  Streamwood  IL      United States
41.877445  -87.723846  Chicago     IL      United States
29.986801  -90.166314  Metairie    LA      United States

有了这么大的数据集,如何在 python 中实现?我听说过 Google 的 API、Nominatim 的 API 和 Geopy 包。

如何 运行 遍历此代码中的所有行?现在我必须在最后一行手动输入纬度和经度。

import csv 
import pandas as pd
import numpy as np
import math
from geopy.geocoders import Nominatim

input_file = "Lat-Log.csv" # file contains ID, Latitude, Longitude
output_file = "output.csv"
df = pd.read_csv(input_file) 

geolocator = Nominatim(user_agent="geoapiExercises")
def city_state_country(coord):
    location = geolocator.reverse(coord, exactly_one=True)
    address = location.raw['address']
    city = address.get('city', '')
    state = address.get('state', '')
    country = address.get('country', '')
    return city, state, country
print(city_state_country("47.470706, -99.704723"))

输出给我('Bowdon'、'North Dakota'、'USA')。我希望通过我的列表将坐标替换为我的列(纬度和经度)到 运行。如何将我的列输入到代码中以 运行 贯穿整个文档?

您想 运行 每行一个函数,这可以使用 apply() 来完成。

有两个问题,即您想要 1) 为函数提供多个参数,以及 2) 取回多个结果。

这些问题解释了如何做这些事情:

  • Return multiple columns from pandas apply()

以下是调整代码以执行此操作的方法:

import pandas as pd
import io
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="geoapiExercises")

s = """Latitude   Longitude  
42.022506  -88.168156  
41.877445  -87.723846  
29.986801  -90.166314"""

df = pd.read_csv(io.StringIO(s), delim_whitespace=True)

def city_state_country(row):
    coord = f"{row['Latitude']}, {row['Longitude']}"
    location = geolocator.reverse(coord, exactly_one=True)
    address = location.raw['address']
    city = address.get('city', '')
    state = address.get('state', '')
    country = address.get('country', '')
    row['city'] = city
    row['state'] = state
    row['country'] = country
    return row

df = df.apply(city_state_country, axis=1)
print(df)

(我用数据帧的内联定义替换了你的 read_csv() 调用。忽略它。这对示例并不重要。我这样做是为了使示例独立。)

数据框的每一行都会调用 city_state_country() 函数。 (axis=1 参数使 apply() 运行 使用行而不是列。)该函数获取纬度和经度,并进行查询。然后,它修改行以包含来自查询的信息。

这会得到以下结果:

    Latitude  Longitude     city      state        country
0  42.022506 -88.168156            Illinois  United States
1  41.877445 -87.723846  Chicago   Illinois  United States
2  29.986801 -90.166314           Louisiana  United States

与您的示例不一样,但 Nominatim 似乎没有 return 两个城市的坐标。 (它称它们为城镇,而不是城市。)