Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have a dataframe with many places and the details of their locations, such as latitude and longitude. What I need to do is to use map API to request json file of each place to get the nearby information around this place and then print out of them.
Everything works great until I try to create a function to repeat the same thing as the same thing I did to any place of my data.
python3
pandas
I can get what I want for anyone location separately, but my function didn't work.
I searched some threads about the same kind of question, such as change the columns or create the new dataframe first, but they didn't help.
def get_nearby_venues(names, prices, latitudes, longitudes):
venues_list=[]
for name, price, lat, lng in zip(names, prices, latitudes, longitudes):
print(name)
# construct urls from page 1 to page 5(the first page will be displayed when page_num=0)
url_list = []
for page_num in range(0, 5):
urls = 'http://api.map.baidu.com/place/v2/search?query=公园$超市$美食$学校$医院$公交车站$银行$电影院&location={},{}&radius=1000&output=json&scope=2&page_size=20&page_num='+str(page_num)+'&ak=(API key)'.format(lat, lng)
url_list.append(urls)
# make request to get json content
results_json_list = []
for each in url_list:
results_json = requests.get(each).json()['results']
# merge all pages json content into one file and all of my location data is stored in it.
results_json_list.extend(results_json)
# I try to use the following code to print out but failed.
# return only relevant information for each nearby venue
for each_item in results_json_list:
venues_list.append([
name,
price,
each_item.get('name'),
each_item.get('location').get('lat'),
each_item.get('location').get('lng'),
each_item.get('detail_info').get('type')])
nearby_venues = pd.DataFrame([item for sublist in venues_list for item in sublist])
# nearby_venues = pd.DataFrame(venues_list)
nearby_venues.columns = ['Apartment',
'Apartment Price',
'Apartment Latitude',
'Apartment Longitude',
'Venue',
'Venue Latitude',
'Venue Longitude',
'Venue Category']
return nearby_venues
# function code ends here
# dataframe data_venues is what I want to the results stored in for each location of my data and dataframe 'Data_map' is my previous dataframe which contains 'Name', 'Categories', 'Latitude', 'Longitude' columns of my data
data_venues = get_nearby_venues(names=Data_map['Name'],
prices=Data_map['Price'],
latitudes=Data_map['Latitude'],
longitudes=Data_map['Longitude']
ERROR MESSAGE code:
ValueError Traceback (most recent call last)
<ipython-input-33-9b269af7a350> in <module>
8 prices=Data_map.['Price'],
9 latitudes=Data_map['Latitude'],
---> 10 longitudes=Data_map['Longitude']
11 )
<ipython-input-32-01b4632eb663> in get_nearby_venues(names, prices, latitudes, longitudes)
44 'Venue Latitude',
45 'Venue Longitude',
---> 46 'Venue Category']
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/generic.py in __setattr__(self, name, value)
5078 try:
5079 object.__getattribute__(self, name)
-> 5080 return object.__setattr__(self, name, value)
5081 except AttributeError:
5082 pass
pandas/_libs/properties.pyx in pandas._libs.properties.AxisProperty.__set__()
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/generic.py in _set_axis(self, axis, labels)
637 def _set_axis(self, axis, labels):
--> 638 self._data.set_axis(axis, labels)
639 self._clear_item_cache()
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/internals/managers.py in set_axis(self, axis, new_labels)
153 raise ValueError(
154 'Length mismatch: Expected axis has {old} elements, new '
--> 155 'values have {new} elements'.format(old=old_len, new=new_len))
157 self.axes[axis] = new_labels
ValueError: Length mismatch: Expected axis has 0 elements, new values have 8 elements
when a df is created already with a single column, you can NOT df.columns = list of more columns
continued
right after you got nearby
insert the following code, it will provide a guidance what is going on. But not to achieve exactly what you want.
nearby = nearby.rename(
columns=dict( zip(
[0,1,2,3],
['Apartment','Apartment Price', 'Apartment Latitude', 'Apartment Longitude']))
for coln in ['Venue','Venue Latitude','Venue Longitude','Venue Category']:
nearby.insert(column=coln, loc=len(nearby.columns), value=np.nan)
the fundamental cause of the error is that, your new data, does NOT have the same amount of columns as your old data, that's why the old method works on the old data but not the new data.
–
–
–
for page_num in range(0, 5):
urls = 'http://api.map.baidu.com/place/v2/search?query=公园$超市$美食$学校$医院$公交车站$银行$电影院&location={},{}&radius=1000&output=json&scope=2&page_size=20&page_num='+str(page_num)+'&ak=(API key)'.format(
into:
for num in range(0, 5):
urls = 'http://api.map.baidu.com/place/v2/search?query=公园$超市$美食$学校$医院$公交车站$银行$电影院&location={},{}&radius=1000&output=json&scope=2&page_size=20&page_num={}&ak=(API key)'.format(
it worked.
I have on idea why I can't ues the previous one to request json file, that's why it said Expected axis has 0 elements
@ugn Thanks for your insight :)
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.