I am aiming to add a few columns based on the existing 'latitude' and 'longitude' columns, where each of the column entry is used to retrieve relevant data from googla api. My method works fine but it takes extremely long to compute for more than 450k data.
Could anyone suggest a more efficient way to iterate through the dataframe, or apply the user-defined function to all rows so that the same goal could be achieved?
```
"""This function takes in a property csv (pandas dataframe) file, and compute distance, time for each property location to Melbourne CBD, using
the latitude and longitude of each property, and return the imputed csv file"""
def add_distance(property_csv):
...
gmaps = googlemaps.Client(key='myAPI')
driving_distance_list_km = []
driving_time_list_mins = []
walking_distance_list_km = []
walking_time_list_mins = []
i=0
for row in property_dict:
print(f"Row {i}, location {row['street_address']}")
origin_latitude, origin_longitude = row['latitude'], row['longitude']
#print(f"Row {i}, location {row[2]}")
#origin_latitude, origin_longitude = row[0], row[1]
driving_distance_matrix = gmaps.distance_matrix([str(origin_latitude) + " " + str(origin_longitude)], [str(destination_latitude) + " " + str(destination_longitude)], mode='driving')
walking_distance_matrix = gmaps.distance_matrix([str(origin_latitude) + " " + str(origin_longitude)], [str(destination_latitude) + " " + str(destination_longitude)], mode='walking')
# individual values
driving_distance_km = pd.to_numeric(pattern.findall(driving_distance_matrix['rows'][0]['elements'][0]['distance']['text'])[0])
driving_time_mins = pd.to_numeric(pattern.findall(driving_distance_matrix['rows'][0]['elements'][0]['duration']['text'])[0])
walking_distance_km = pd.to_numeric(pattern.findall(walking_distance_matrix['rows'][0]['elements'][0]['distance']['text'])[0])
walking_time_mins = pd.to_numeric(pattern.findall(walking_distance_matrix['rows'][0]['elements'][0]['duration']['text'])[0])
# store values to corresponding list
...
i += 1
...
return property_csv
Many thanks!