Python list index out of range error questions

Asked 2 years ago, Updated 2 years ago, 16 views

Hello, I am a college student studying Python. While studying Python, I kept encountering the following error and posted a question like this. No matter how hard I think about it, I can't judge what the problem is just by looking at the error, so I'm asking you a question Currently, we are trying to extract park name data from the Seoul City Park data to create a new data frame and use the function to retrieve location information of address, latitude, and longitude, but the following error continues to occur. Help me

Traceback (most recent call last): File "", line 3, in File "", line 10, in getAddr IndexError: list index out of range

//import Google Maps
import googlemap_key
import pandas as pd




def getAddr(name):
    map = gmaps.geocode(name, language='ko')
    addr = map[0].get('formatted_address')
    tmp_loc = map[0].get('geometry').get('location')
    return addr, tmp_loc['lat'], tmp_loc['lng']


# Loading data

Park_in_Seoul = pd.read_csv('/Users/ikwonjobs/Documents/data/Seoul_Park.csv', encoding='utf-8')
Park_Seoul = pd.DataFrame()
Park_Seoul['Park'] = Park_in_Seoul.Park Name

Park_Seoul.to_csv('/Users/ikwonjobs/Documents/data/Park_Seoul.csv', encoding = 'utf-8')

print(Park_Seoul.head())

#Add Data



pd.read_csv('/Users/ikwonjobs/Documents/data/Park_Seoul.csv',index_col=0,encoding='utf-8')

park_addr = []
park_lat = []
park_lng = []
gmaps = googlemaps.Client(key=googlemap_key.gmaps_key)
For park in park_Seoul.Park:
    addr,lat, lng = getAddr(park)
    park_addr.append(addr)
    park_lat.append(lat)
    park_lng.append(lng)

python

2022-09-21 21:23

1 Answers

list index out of range is an error that occurs when index values such as lists or tuples are longer than the length.

If you look at the error message,

    map = gmaps.geocode(name, language='ko')
    addr = map[0].get('formatted_address')  # <<< list index out of range

It appears to have occurred at . That is, in map[0].

If map was returned to None, the object not subscriable error would have occurred, so gmap.geocode returned by the function appears to be an empty list (=) with a length of 0. Why it was returned like that, I think we should check and compare whether it is returned properly when name is inserted that gives an accurate return.

Additionally, the csv data provided by the Seoul Metropolitan Government or the government site is usually encoded as euc-kr rather than utf-8. If you read it in the wrong encoding, the address will be broken.

I think we need to debug it a little more, so please try it and add questions if there is anything wrong. (Please also tell me what data you use.)


2022-09-21 21:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.