- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试完成 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 在我尝试使用定义的函数的下一个单元格中被标记。这让我认为问题一定出在函数本身。我必须根据我的独特作业对其进行一些修改,因此这可能是问题的一部分。以下是我在基本输入之外对函数所做的更改:
波特兰的一些社区没有在我的 API 请求中返回的任何 field ,并且标记了“KeyError”,因为它们在返回的 json 中没有“group”部分,因此我必须添加“try/except"行来排除没有返回 field 的社区。当我第一次运行它并允许单元格执行时,这工作得很好。但是,在下一个单元格中使用该函数会导致“ValueError”标记。
根据 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/
您好,我很确定我的问题很愚蠢,但我无法弄清楚它对我的生活有何影响。我有这个家庭作业,它基本上是为了加强我们在类里面学到的关于多态性的知识(顺便说一下,这是 C++)。该程序的基础是一个名为 shape
我是新手,所以需要任何帮助,当我要求一个例子时,我的教授给我了这段代码,我希望有一个工作模型...... from numpy import loadtxt import numpy as np fr
CSS 形状边距 和 外型不适用于我的系统。我正在使用最新版本的 Chrome。我唯一能想到的是我的操作系统是 Windows 7。这应该是一个问题吗? 这是JSFiddle .但是,由于在您的系统上
#tf.shape(tensor)和tensor.shape()的区别 ?
我要求提示以下问题。如何从事件表添加到指定的单元格形状?当我知道名称但不知道如何为...中的每个形状实现论坛时,我可以添加形状 目前我有这样的事情: Sub loop() Dim a As Integ
我在 Excel 中有一个流程设计(使用形状、连接器等)。 我需要的是有一个矩阵,每个形状都有所有的前辈和所有的后继者。 在 VBA 中,为此我正在尝试执行以下操作: - 我列出了所有的连接器(Sha
我正在使用 JavaFX 编写一个教育应用程序,用户可以在其中绘制和操作贝塞尔曲线 Line、QuadCurve 和 CubicCurve。这些曲线应该能够用鼠标拖动。我有两种选择: 1- 使用类 L
我正在尝试绘制 pandas 系列中列的直方图 ('df_plot')。因为我希望 y 轴是百分比(而不是计数),所以我使用权重选项来实现这一点。正如您在下面的堆栈跟踪中发现的那样,权重数组和数据系列
我尝试在 opencv dnn 中实现一个 tensorflow 模型。这是我遇到的错误: OpenCV: Can't create layer "flatten_1/Shape" of type "
我目前正在用 Java 开发一款游戏,我一直在尝试弄清楚如何在 Canvas 上绘制一个形状(例如圆形),在不同的形状(例如正方形)之上,但是只绘制与正方形相交的圆的部分,类似于 Photoshop
import cv2 import numpy as np import sys import time import os cap = cv2.VideoCa
我已经成功创建了 Keras 序列模型并对其进行了一段时间的训练。现在我试图做出一些预测,但即使使用与训练阶段相同的数据,它也会失败。 我收到此错误:{ValueError}检查输入时出错:预期 em
我正在尝试逐行分解程序。 Y 是一个数据矩阵,但我找不到任何关于 .shape[0] 究竟做了什么的具体数据。 for i in range(Y.shape[0]): if Y[i] == -
我正在尝试运行代码,但它给了我这个错误: 行,列,_ = frame.shape AttributeError:“tuple”对象没有属性“shape” 我正在使用OpenCV和python 3.6,
我想在 JavaFx 中的 Pane 上显示形状。我正在使用从空间数据库中选择的 Oracle JGeometry 对象,它有一个方法 createShape() 但它返回 java.awt.Shap
在此代码中: import pandas as pd myj='{"columns":["tablename","alias_tablename","real_tablename","
我正在尝试将 API 结果应用于两列。 下面是我的虚拟数据框。不幸的是,这不是很容易重现,因为我使用的是带有 key 和密码的 API...这只是为了让您了解尺寸。 但我希望也许有人能发现一个明显的问
我的代码是: final String json = getObjectMapper().writeValueAsString(JsonView.with(graph) .onClas
a=np.arange(240).reshape(3,4,20) b=np.arange(12).reshape(3,4) c=np.zeros((3,4),dtype=int) x=np.arang
我正在尝试从张量中提取某些数据,但出现了奇怪的错误。在这里,我将尝试生成错误: a=np.random.randn(5, 10, 5, 5) a[:, [1, 6], np.triu_indices(
我是一名优秀的程序员,十分优秀!