gpt4 book ai didi

python - 如何解析 "ValueError: Shape of passed values is (228, 1), indices imply (228, 7)"

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:34 29 4
gpt4 key购买 nike

我正在尝试完成 coursera 类(class)的作业,但很难让我的代码的某个方面正常工作。

我正在使用 foursquare API 来探索波特兰的社区,并查找哪些社区有书店(和类似的场所)。我即将执行它,但我一直标记上述 ValueError,并且不知道如何重组我的 DF 以使其具有正确的形状。

这是我的代码:

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()

我从类(class)中之前的实验中获取了原始函数,所以我知道它应该可以工作。第一个单元格实际上执行得很好,但是 ValueError 在我尝试使用定义的函数的下一个单元格中被标记。这让我认为问题一定出在函数本身。我必须根据我的独特作业对其进行一些修改,因此这可能是问题的一部分。以下是我在基本输入之外对函数所做的更改:

  1. 波特兰的一些社区没有在我的 API 请求中返回的任何 field ,并且标记了“KeyError”,因为它们在返回的 json 中没有“group”部分,因此我必须添加“try/except"行来排除没有返回 field 的社区。当我第一次运行它并允许单元格执行时,这工作得很好。但是,在下一个单元格中使用该函数会导致“ValueError”标记。

  2. 根据 stackoverflow 帖子中另一位用户的建议(该帖子与我有类似问题),我尝试通过将venues_list.append 更改为 .extend 来修复下一个单元格中的 ValueError。似乎没有多大帮助,因为我仍然收到 ValueError,但在它被标记为具有 1 个元素而不是 7 个元素之前(相同的问题,不同的形式)。

任何帮助将不胜感激,这是一个困难的项目,我能够利用自己的资源取得很大的进展,但这个问题完全困扰了我。预先感谢您!

此外,这里是完整的 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)

最佳答案

问题可能归结为您的 except 子句,该子句没有像 try 子句那样包装在嵌入式元组中。因此,venues_list 扩展了底层集合的每个元素。因此,您传递的是 [(tuple of vals), val1, val2, val3, 而不是 [(tuple of vals), tuple(val1, val2, val3), (tuple of vals)] (vals 元组)]DataFrame 构造函数中。

except KeyError:
venues_list.extend([(
name,
lat,
lng)])

还应考虑捕获可能由于 API 请求调用而不仅仅是返回的 json 导致的任何异常。另外,包含 numpy.nan 来查找缺失的列(因此数据框中会产生 NaN 而不是 None 结果)。

except Exception as e:
print(e.message)

venues_list.extend([(
name,
lat,
lng,
np.nan,
np.nan,
np.nan,
np.nan)])

关于python - 如何解析 "ValueError: Shape of passed values is (228, 1), indices imply (228, 7)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59981524/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com