0

I am using Google Maps API to collect distance data and most probably not all locations can retrieve distance information, so I get an error "ValueError: Length of values does not match length of index". Any tips how to update the code to fix it?

lat_origin = df["lat1"].tolist()
long_origin = df["lon1"].tolist()
lat_destination = df["lat2"].tolist()
long_destination = df["lon2"].tolist()
distance = []
for i in range(len(long_destination)):
    url = f"https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins={lat_origin[i]},{long_origin[i]}&destinations={lat_destination[i]}%2C{long_destination[i]}&key={google_key}&channel={channel_id}"
    r=requests.get(url)
    data = r.json()
    try:
        distance.append(data['rows'][0]['elements'][0]['distance']['value'])
    except:
        pass
distance

distance2 = []
for i in range(len(distance)):
    distance2.append(distance[i])
df["Distance_in_Meters"] = distance2
Laura
  • 1
  • 1
  • It seems that the length of distance2 array is not same as the data in df. Check https://stackoverflow.com/questions/42382263/valueerror-length-of-values-does-not-match-length-of-index-pandas-dataframe-u/42382321 – Divakar Patil Jan 11 '21 at 13:08
  • Yes, possibly not all locations within df get the distance retrieved from google maps. However I am not sure how I can update the code, that for example I fill in value "NA" for values that are not matched, so it results to the same amount of data or drop the unmatched values. – Laura Jan 11 '21 at 13:22

1 Answers1

0

You can do something like this to append NA Values to your list

import numpy as np
import pandas as pd

l = [1,2,3]
# Need to convert all the elements in list to float as NAN does not have 
# equivalent Int value in Pandas. 
l = list(map(lambda x: float(x), l))
right_padding = len(df) - len(l)
left_padding = 0
arr = np.pad(l, pad_width=(left_padding, right_padding), mode='constant', 
constant_values=(np.nan,))
print(arr)
df['B'] = arr
Divakar Patil
  • 323
  • 2
  • 11