[英]Is there a way to output a dataframe containing latitude and longitude given City and Country in an excel file?
我有一個包含兩列的 excel 文件。 第一列是“城市”,第二列是“國家”。 我希望我的 python 代碼遍歷每一行並找到每一行的緯度和經度。 python 代碼根據需要創建了兩個新列“Latitude”和“Longitude”,但對所有值都返回 None。 任何幫助表示贊賞。
import pandas as pd
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="Your_Name")
df = pd.read_excel("location.xlsx")
longitude = []
latitude = []
city = df["City"]
country = df["Country"]
for i in df.index:
loc = geolocator.geocode(city + ',' + country)
if loc is None:
latitude.append(None)
longitude.append(None)
else:
latitude.append(loc.latitude)
longitude.append(loc.longitude)
df["Longitude"] = longitude
df["Latitude"] = latitude
print(df)
使用下面給定的 dataframe df
:
import pandas as pd
data = {"City": ["London", "Berlin", "Madrid", "Rome",
"Paris", "Vienna", "Bucharest", "Hamburg",
"Budapest", "Warsaw", "Barcelona",
"Munich", "Milan"],
"Country": ["England", "Germany", "Spain", "Italy",
"France", "Austria", "Romania",
"Germany", "Hungary", "Poland", "Spain",
"Germany", "Italy"]
}
df = pd.DataFrame(data)
您可以使用geolocator.geocode
獲取城市/國家/地區的緯度/經度:
from geopy.geocoders import Nominatim
out = (
df.assign(Geocodes= (df['City'] + ", " + df['Country']).apply(geolocator.geocode))
.assign(Latitude = lambda x: [g.latitude for g in x['Geocodes']],
Longitude= lambda x: [g.longitude for g in x['Geocodes']])
.drop(columns='Geocodes')
)
print(out)
City Country Latitude Longitude
0 London England 51.507322 -0.127647
1 Berlin Germany 52.517037 13.388860
2 Madrid Spain 40.416705 -3.703582
3 Rome Italy 41.893320 12.482932
4 Paris France 48.858890 2.320041
5 Vienna Austria 48.208354 16.372504
6 Bucharest Romania 44.436141 26.102720
7 Hamburg Germany 53.550341 10.000654
8 Budapest Hungary 47.497994 19.040359
9 Warsaw Poland 52.231958 21.006725
10 Barcelona Spain 41.382894 2.177432
11 Munich Germany 48.137108 11.575382
12 Milan Italy 45.464194 9.189635
您錯過了索引城市和國家系列。
只需在您的代碼中嘗試loc = geolocator.geocode(city[i] + ',' + country[i])
。 它對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.