Home > Blockchain >  How to save the results of a function as a new CSV?
How to save the results of a function as a new CSV?

Time:11-05

The code is required to take addresses from a csv file and then use a function to compute the corresponding Latitudes and Longitudes. While I get the correct Latitudes and Longitudes but I am unable to save them to a new csv file.

import requests import urllib.parse import pandas as pd

#function to get the Coordinates:

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 is called to get the 5 Address Values from the CSV File and pass on to the function

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)

Output is:

Latitude  Longitude
34.0096961 71.8990106
34.0123846 71.5787458
33.6038766 73.048136
33.6938118 73.0651511
24.8546842 67.0207055

I want to save this output into a new file and I am unable to get the results.

CodePudding user response:

Just a small modification might help

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)

CodePudding user response:

#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= ' ') 
  • Related