Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

python - How to solve error: "Length of values does not match length of index" for google maps API results

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...