該代碼需要從 csv 檔案中獲取地址,然后使用函式來計算相應的緯度和經度。雖然我得到了正確的緯度和經度,但我無法將它們保存到新的 csv 檔案中。
匯入請求 import urllib.parse import pandas as pd
#function 獲取坐標:
def lat_long(add):
url = 'https://nominatim.openstreetmap.org/search/' urllib.parse.quote(add) '?format=json'
response = requests.get(url).json()
print(response[0]["lat"], response[0]["lon"])
return
#function 被呼叫以從 CSV 檔案中獲取 5 個地址值并傳遞給函式
df = pd.read_csv('C:\\Users\\Umer Abbas\\Desktop\\lat_long.csv')
i = 0
print("Latitude","","Longitude")
for i in range (0,5):
add = df._get_value(i, 'Address')
lat_long(add)
輸出是:
Latitude Longitude
34.0096961 71.8990106
34.0123846 71.5787458
33.6038766 73.048136
33.6938118 73.0651511
24.8546842 67.0207055
我想將此輸出保存到一個新檔案中,但我無法獲得結果。
uj5u.com熱心網友回復:
只是一個小的修改可能會有所幫助
def lat_long(add):
url = 'https://nominatim.openstreetmap.org/search/' urllib.parse.quote(add) '?format=json'
response = requests.get(url).json()
print(response[0]["lat"], response[0]["lon"])
Lat = response[0]["lat"]
Long = response[0]["lon"]
return Lat, Long
Lat_List = []
Long_List = []
df = pd.read_csv('C:\\Users\\Umer Abbas\\Desktop\\lat_long.csv')
i = 0
print("Latitude","","Longitude")
for i in range (0,5):
add = df._get_value(i, 'Address')
Lat =lat_long(add)[0]
Long = lat_long(add)[1]
Lat_List.append(Lat)
Long_List.append(Long)
df1 = pd.DataFrame(data, columns=['Latitude', 'Longitude])
df1['Latitude'] = Lat_List
df1['Longitude'] = Long_List
df1.to_csv("LatLong.csv)
uj5u.com熱心網友回復:
#one line of change here
def lat_long(add):
url = 'https://nominatim.openstreetmap.org/search/' urllib.parse.quote(add) '?format=json'
response = requests.get(url).json()
print(response[0]["lat"], response[0]["lon"])
return response[0]["lat"], response[0]["lon"] # return the lat and long
# three lines added here
df = pd.read_csv('C:\\Users\\Umer Abbas\\Desktop\\lat_long.csv')
i = 0
l=[] # define empty list
print("Latitude","","Longitude")
for i in range (0,5):
add = df._get_value(i, 'Address')
l.append(lat_long(add)) # append to the empty l
# create a dataframe and output as csv
pd.DataFrame(l, columns=['Longitude', 'Latitude']).to_csv('test.csv', sep= ' ')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528194.html
上一篇:如何在顫振中使用動態地圖名稱
下一篇:迭代嵌套字典并過濾特定欄位
