python - ValueError:长度不匹配:预期轴有 0 个元素,新值有 8 个元素
问题描述
我有一个包含许多地方的数据框及其位置的详细信息,例如纬度和经度。我需要做的是使用地图API请求每个地方的json文件来获取这个地方附近的信息,然后打印出来。
一切都很好,直到我尝试创建一个函数来重复与我对数据的任何位置所做的相同的事情。
python3熊猫
我可以分别为任何位置获得我想要的东西,但我的功能不起作用。
我搜索了一些关于同类问题的线程,例如更改列或首先创建新的数据框,但它们没有帮助。
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,
lat,
lng,
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']
47
48
/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)
636
637 def _set_axis(self, axis, labels):
--> 638 self._data.set_axis(axis, labels)
639 self._clear_item_cache()
640
/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))
156
157 self.axes[axis] = new_labels
ValueError: Length mismatch: Expected axis has 0 elements, new values have 8 elements
解决方案
从以下位置更改 URL 的格式后:
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)
进入:
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(
lat,
lng,
num)
有效。
我知道为什么我不能使用前一个来请求 json 文件,这就是为什么它说预期轴有 0 个元素
@ugn 感谢您的洞察力:)
推荐阅读
- jmeter - HTTP 请求中文件协议的使用
- npm - npm - 修复 package-lock.json 中易受攻击的依赖项
- java - Cloud SQL 和 App Engine 之间的连接超时
- reactjs - Formik 重置错误
- python - 如何重塑文本数据以适合 keras 中的 LSTM 模型
- php - Laravel 5.8 公用文件夹重定向到“/索引”页面
- sorting - 如何根据谷歌应用脚本中的电子表格日期发送电子邮件?
- c# - 如何访问 .Name 正则表达式组?
- amazon-web-services - 如何仅将 NAT 网关用于出站流量
- python - 添加小部件时如何更新 Kivy ActionGroup 显示?