python-如何解决;ValueError:传递值的形状为(228,1),索引暗示(228,7)";
我正试图完成一个coursera课程的作业,我的代码的一个方面很难正常工作 我正在使用foursquare API探索波特兰的社区,并找出哪些社区有书店(以及类似的场所)。我即将让它执行,但我一直在标记上面的ValueError,不知道如何重新构造DF以使其具有正确的形状 这是我的密码:python-如何解决;ValueError:传递值的形状为(228,1),索引暗示(228,7)";,python,pandas,foursquare,valueerror,Python,Pandas,Foursquare,Valueerror,我正试图完成一个coursera课程的作业,我的代码的一个方面很难正常工作 我正在使用foursquare API探索波特兰的社区,并找出哪些社区有书店(以及类似的场所)。我即将让它执行,但我一直在标记上面的ValueError,不知道如何重新构造DF以使其具有正确的形状 这是我的密码: def getNearbyVenues(names, latitudes, longitudes, limit=500): venues_list=[] for name, lat, lng
def getNearbyVenues(names, latitudes, longitudes, limit=500):
venues_list=[]
for name, lat, lng in zip(names, latitudes, longitudes):
print(name)
url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&ll={},{}&v={}&query={}&radius={}&limit={}'.format(
CLIENT_ID,
CLIENT_SECRET,
VERSION,
lat,
lng,
query,
radius,
LIMIT)
try:
results = requests.get(url, "none").json()['response']['groups'][0]['items']
venues_list.extend([(
name,
lat,
lng,
v['venue']['name'],
v['venue']['location']['lat'],
v['venue']['location']['lng'],
v['venue']['categories'][0]['name']) for v in results])
except KeyError:
venues_list.extend([
name,
lat,
lng])
nearby_venues = pd.DataFrame(venues_list, columns = ['Neighborhood',
'Neighborhood Latitude',
'Neighborhood Longitude',
'Venue',
'Venue Latitude',
'Venue Longitude',
'Venue Category'])
return(nearby_venues)
*** NEXT CELL***
PDX_venues = getNearbyVenues(names=PDX_NeighDF['Neighborhood'],
latitudes=PDX_NeighDF['Latitude'],
longitudes=PDX_NeighDF['Longitude']
)
PDX_venues.head()
在本课程中,我从以前的实验室获取了原始函数,因此我知道它应该可以工作。第一个单元格实际上执行得很好,但ValueError在下一个单元格中被标记,我尝试使用定义的函数。这让我觉得问题一定出在函数本身。为了我的独特任务,我不得不对它做一些修改,所以这可能是问题的一部分。以下是我在基本输入之外对函数所做的更改:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
1677 blocks = [
-> 1678 make_block(values=blocks[0], placement=slice(0, len(axes[0])))
1679 ]
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/blocks.py in make_block(values, placement, klass, ndim, dtype, fastpath)
3283
-> 3284 return klass(values, ndim=ndim, placement=placement)
3285
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/blocks.py in __init__(self, values, placement, ndim)
2791
-> 2792 super().__init__(values, ndim=ndim, placement=placement)
2793
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/blocks.py in __init__(self, values, placement, ndim)
127 "Wrong number of items passed {val}, placement implies "
--> 128 "{mgr}".format(val=len(self.values), mgr=len(self.mgr_locs))
129 )
ValueError: Wrong number of items passed 1, placement implies 7
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-40-66be6cf8c7d3> in <module>
1 PDX_venues = getNearbyVenues(names=PDX_NeighDF['Neighborhood'],
2 latitudes=PDX_NeighDF['Latitude'],
----> 3 longitudes=PDX_NeighDF['Longitude']
4 )
5
<ipython-input-39-53e5a94bf83d> in getNearbyVenues(names, latitudes, longitudes, limit)
39 'Venue Latitude',
40 'Venue Longitude',
---> 41 'Venue Category'])
42
43 return(nearby_venues)
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
462 mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype)
463 else:
--> 464 mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
465 else:
466 mgr = init_dict({}, index, columns, dtype=dtype)
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/construction.py in init_ndarray(values, index, columns, dtype, copy)
211 block_values = [values]
212
--> 213 return create_block_manager_from_blocks(block_values, [columns, index])
214
215
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
1686 blocks = [getattr(b, "values", b) for b in blocks]
1687 tot_items = sum(b.shape[0] for b in blocks)
-> 1688 construction_error(tot_items, blocks[0].shape[1:], axes, e)
1689
1690
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/managers.py in construction_error(tot_items, block_shape, axes, e)
1717 raise ValueError("Empty data passed with indices specified.")
1718 raise ValueError(
-> 1719 "Shape of passed values is {0}, indices imply {1}".format(passed, implied)
1720 )
1721
ValueError: Shape of passed values is (228, 1), indices imply (228, 7)
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/managers.py,位于从块(块、轴)创建块的管理器中
1677块=[
->1678生成块(值=块[0],位置=切片(0,透镜(轴[0]))
1679 ]
make_块中的~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/blocks.py(值、位置、klass、ndim、数据类型、快速路径)
3283
->3284返回klass(值,ndim=ndim,placement=placement)
3285
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/blocks.py in uuu___________(self,values,placement,ndim)
2791
->2792 super()
2793
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/blocks.py in uuu___________(self,values,placement,ndim)
127“传递的项数错误{val},位置暗示”
-->128“{mgr}”。格式(val=len(self.values),mgr=len(self.mgr_locs))
129 )
ValueError:传递的项目数错误1,放置意味着7
在处理上述异常期间,发生了另一个异常:
ValueError回溯(最近一次调用上次)
在里面
1 PDX_场馆=GetNearByVinces(名称=PDX_NeighDF[“邻居”],
2纬度=PDX_NeighDF[“纬度”],
---->3经度=PDX_NeighDF[“经度”]
4 )
5.
在GetNearBy场馆(名称、纬度、经度、极限)
39‘场地纬度’,
40‘场地经度’,
--->41“场馆类别”])
42
43返回(附近的场馆)
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/frame.py in\uuuuu init\uuuuu(self,data,index,columns,dtype,copy)
462 mgr=数组\u到\u mgr(数组、列、索引、列、数据类型=数据类型)
463其他:
-->464 mgr=init_ndarray(数据、索引、列、数据类型=数据类型、副本=副本)
465其他:
466 mgr=init_dict({},索引,列,dtype=dtype)
init_ndarray中的~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/construction.py(值、索引、列、数据类型、副本)
211块_值=[值]
212
-->213从块返回创建块管理器(块值,[列,索引])
214
215
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/managers.py,位于从块(块、轴)创建块的管理器中
1686块=[getattr(b,“值”,b)表示块中的b]
1687 tot_项目=总和(块中b的b形状[0]
->1688构造错误(总项目、块[0]。形状[1]、轴、e)
1689
1690
~/conda/envs/python/lib/python3.6/site-packages/pandas/core/internals/managers.py施工错误(tot项目、块形状、轴、e)
1717 raise VALUERROR(“通过指定索引传递的空数据”)
1718升值错误(
->1719“传递值的形状为{0},索引暗示{1}”。格式(传递,暗示)
1720 )
1721
ValueError:传递值的形状为(228,1),索引暗示(228,7)
问题可能归结为您的子句,但子句除外,它不像try
子句那样包装在嵌入式元组中。因此,场馆列表
扩展了基础集合的每个元素。因此,您将[(VAL的元组)、元组(val1、val2、val3)、(VAL的元组)]
传递到[(VAL的元组)、val1、val2、val3、(VAL的元组)]
构造函数中
except KeyError:
venues_list.extend([(
name,
lat,
lng)])
考虑捕获任何可能由API re引起的异常
except Exception as e:
print(e.message)
venues_list.extend([(
name,
lat,
lng,
np.nan,
np.nan,
np.nan,
np.nan)])