У меня проблемы со следующим кодом:
for i in np.arange(37,finaldf.shape[0]):
# We choose to search by category with a 500m radius. radius = 500 LIMIT = 100 category_id = '4bf58dd8d48988d102951735' #ID for Accessory stores
latitude = finaldf['Latitude'][i] longitude = finaldf['Longitude'][i]
# Define the corresponding URL url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&v={}&categoryId={}&radius={}&limit={}'.format(CLIENT_ID, CLIENT_SECRET, latitude, longitude, VERSION, category_id, radius, LIMIT)
# Send the GET Request results = requests.get(url).json()
# Get relevant part of JSON and transform it into a pandas dataframe
# assign relevant part of JSON to venues venues = results['response']['venues']
# tranform venues into a dataframe dataframe = json_normalize(venues) dataframe.head()
# keep only columns that include venue name, and anything that is associated with location filtered_columns = ['name', 'categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id'] dataframe_filtered = dataframe.loc[:, filtered_columns]
# function that extracts the category of the venue def get_category_type(row):
try:
categories_list = row['categories']
except:
categories_list = row['venue.categories']
if len(categories_list) == 0:
return None
else:
return categories_list[0]['name']
# filter the category for each row dataframe_filtered['categories'] = dataframe_filtered.apply(get_category_type, axis=1)
# clean column names by keeping only last term dataframe_filtered.columns = [column.split('.')[-1] for column in dataframe_filtered.columns]
print(str(i) + ') The number of shops in '
+finaldf['Neighbourhood'][i] + ' is ' +str(dataframe_filtered.shape[0]) + '\n') N_shop.append(dataframe_filtered.shape[0])
Эта итерация заставляет меня подсчитывать для каждого района количество магазинов, которое соответствует, но при его выполнении я получаю следующую ошибку:
KeyError Traceback (most recent call last)
<ipython-input-109-94d4817fe1e7> in <module>
6 category_id = '4bf58dd8d48988d102951735' #ID for Accessory stores
7
----> 8 latitude = finaldf['Latitude'][i]
9 longitude = finaldf['Longitude'][i]
10
/opt/conda/envs/Python36/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
866 key = com.apply_if_callable(key, self)
867 try:
--> 868 result = self.index.get_value(self, key)
869
870 if not is_scalar(result):
/opt/conda/envs/Python36/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
4372 try:
4373 return self._engine.get_value(s, k,
-> 4374 tz=getattr(series.dtype, 'tz', None))
4375 except KeyError as e1:
4376 if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 38
Конечный df состоит из 5 столбцов и 39 строк, в которых расположены почтовый индекс, район, район, долгота и широта, поскольку затем я буду использовать эти данные для их определения на карте. Я искал нулевые значения, или у меня есть другой тип формата, но я не нашел ни одного. Что не так? Поскольку из того, что я понимаю, есть строка (38), которая является причиной ошибки. Спасибо за помощь.