ValueError:传递的项目数量错误 - 含义和建议?
我正在收到错误:
value error:错误的项目数量错误3,放置意味着1
,我正在努力弄清楚哪里以及如何开始解决问题。
我真的不理解错误的含义;这使我很难进行故障排除。我还包括了jupyter笔记本中触发错误的代码块。
数据很难附加;因此,我不是在寻找任何人试图为我重新发现这个错误。我只是在寻找一些有关如何解决此错误的反馈。
KeyError Traceback (most recent call last)
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance)
1944 try:
-> 1945 return self._engine.get_loc(key)
1946 except KeyError:
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)()
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)()
KeyError: 'predictedY'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py in set(self, item, value, check)
3414 try:
-> 3415 loc = self.items.get_loc(item)
3416 except KeyError:
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py in get_loc(self, key, method, tolerance)
1946 except KeyError:
-> 1947 return self._engine.get_loc(self._maybe_cast_indexer(key))
1948
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)()
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)()
KeyError: 'predictedY'
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-95-476dc59cd7fa> in <module>()
26 return gp, results
27
---> 28 gp_dailyElectricity, results_dailyElectricity = predictAll(3, 0.04, trainX_dailyElectricity, trainY_dailyElectricity, testX_dailyElectricity, testY_dailyElectricity, testSet_dailyElectricity, 'Daily Electricity')
<ipython-input-95-476dc59cd7fa> in predictAll(theta, nugget, trainX, trainY, testX, testY, testSet, title)
8
9 results = testSet.copy()
---> 10 results['predictedY'] = predictedY
11 results['sigma'] = sigma
12
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
2355 else:
2356 # set column
-> 2357 self._set_item(key, value)
2358
2359 def _setitem_slice(self, key, value):
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
2422 self._ensure_valid_index(value)
2423 value = self._sanitize_column(key, value)
-> 2424 NDFrame._set_item(self, key, value)
2425
2426 # check if we are modifying a copy
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
1462
1463 def _set_item(self, key, value):
-> 1464 self._data.set(key, value)
1465 self._clear_item_cache()
1466
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py in set(self, item, value, check)
3416 except KeyError:
3417 # This item wasn't present, just insert at end
-> 3418 self.insert(len(self.items), item, value)
3419 return
3420
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py in insert(self, loc, item, value, allow_duplicates)
3517
3518 block = make_block(values=value, ndim=self.ndim,
-> 3519 placement=slice(loc, loc + 1))
3520
3521 for blkno, count in _fast_count_smallints(self._blknos[loc:]):
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py in make_block(values, placement, klass, ndim, dtype, fastpath)
2516 placement=placement, dtype=dtype)
2517
-> 2518 return klass(values, ndim=ndim, fastpath=fastpath, placement=placement)
2519
2520 # TODO: flexible with index=None and/or items=None
C:\Users\brennn1\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py in __init__(self, values, placement, ndim, fastpath)
88 raise ValueError('Wrong number of items passed %d, placement '
89 'implies %d' % (len(self.values),
---> 90 len(self.mgr_locs)))
91
92 @property
ValueError: Wrong number of items passed 3, placement implies 1
我的代码如下:
def predictAll(theta, nugget, trainX, trainY, testX, testY, testSet, title):
gp = gaussian_process.GaussianProcess(theta0=theta, nugget =nugget)
gp.fit(trainX, trainY)
predictedY, MSE = gp.predict(testX, eval_MSE = True)
sigma = np.sqrt(MSE)
results = testSet.copy()
results['predictedY'] = predictedY
results['sigma'] = sigma
print ("Train score R2:", gp.score(trainX, trainY))
print ("Test score R2:", sklearn.metrics.r2_score(testY, predictedY))
plt.figure(figsize = (9,8))
plt.scatter(testY, predictedY)
plt.plot([min(testY), max(testY)], [min(testY), max(testY)], 'r')
plt.xlim([min(testY), max(testY)])
plt.ylim([min(testY), max(testY)])
plt.title('Predicted vs. observed: ' + title)
plt.xlabel('Observed')
plt.ylabel('Predicted')
plt.show()
return gp, results
gp_dailyElectricity, results_dailyElectricity = predictAll(3, 0.04, trainX_dailyElectricity, trainY_dailyElectricity, testX_dailyElectricity, testY_dailyElectricity, testSet_dailyElectricity, 'Daily Electricity')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不确定这与您的问题是否相关,但是将来可能与其他人有关:我也有类似的错误。原来,DF是空的(零行),这就是导致我命令中错误的原因。
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
此错误的另一个原因是,当您在数据框架上应用功能时,有两个具有相同名称的列。
Another cause of this error is when you apply a function on a DataFrame where there are two columns with the same name.
从Pandas 1.3.x开始,不允许将对象(例如像嵌入的EagerTensor一样)填充到列中。
Starting with pandas 1.3.x it's not allowed to fill objects (e.g. like an eagertensor from an embedding) into columns.
https://github.com/pandas-dev/pandas/blame/master/pandas/core/internals/blocks.py
因此,ValueError:错误的项目数量错误3,放置意味着1时,当您传递了许多参数时,就会发生1个,但方法仅支持少数参数。例如 -
在上面的代码中,我试图将full_col分为两个子列名称为-first_name&amp; last_name,所以在这里我会收到错误,因为相反,我只传递一个参数的列列表。
因此避免这种情况 - 使用另一个子列表
So ValueError: The wrong number of items passed 3, placement implies 1 occurs when you're passing to many arguments but method supports only a few. for example -
In the above code, I'm trying to split Full_col into two sub-columns names as -First_Name & Last_Name, so here I'll get the error because instead list of columns the columns I'm passing only a single argument.
So to avoid this - use another sub-list
仅将其添加为答案:嵌套方法和放错封闭括号也会抛出此错误,例如:
March15_totals = March15_t.t.assign(SUM_MARCH15_T = MARCH15_T = MARCH15_T [{{“ 2021-03-15) ,“ 2021-03-17”,“ 2021-03-18”,“ 2021-03-19”,“ 2021-03-20”,“ 2021-03-21”}])。
与(正确的)版本:
March15_totals = March15_t.assign(SUM_MARCH15_T = MARCH15_T [{“ 2021-03-15”,“ 2021-03-16”,“ 2021-03-17”,“ 2021-03-17”,“ 2021-03-18”,“ 2021-03”,“ 2021-03 ”}]。
-19“,“ 2021-03-20”,“ 2021-03-21 我的错误。
Just adding this as an answer: nesting methods and misplacing closed brackets will also throw this error, ex:
march15_totals= march15_t.assign(sum_march15_t=march15_t[{"2021-03-15","2021-03-16","2021-03-17","2021-03-18","2021-03-19","2021-03-20","2021-03-21"}]).sum(axis=1)
Versus the (correct) version:
march15_totals= march15_t.assign(sum_march15_t=march15_t[{"2021-03-15","2021-03-16","2021-03-17","2021-03-18","2021-03-19","2021-03-20","2021-03-21"}].sum(axis=1))
This is probably common sense to most of you but I was quite puzzled until I realized my mistake.
当我尝试将单列数据框架(
df
)转换为系列时,我遇到了这个错误,pd.series(df)
。我解决了这个问题的
问题是,数据框中的值是列表:
当我打印数据框时,它并没有显示出很难追踪的括号。
I got this error when I was trying to convert a one-column dataframe,
df
, into a Series,pd.Series(df)
.I resolved this with
The problem was that the values in the dataframe were lists:
When I was printing the dataframe it wasn't showing the brackets which made it hard to track down.
这对我有用。
This one worked for me.
通常,错误
valueerror:错误的项目数量错误3,位置意味着1
表明您试图将太多鸽子放在太少的鸽子孔中。在这种情况下,等式结果的右侧值
['predictiony'] = Predictyy
试图将3个“物品”放入一个只允许一个的容器中。由于左侧是一个数据框列,并且可以接受该(列)维度的多个项目,因此您应该看到另一个维度上的项目太多。
在这里,看来您正在使用Sklearn进行建模,这是
Gaussian_process.gaussianprocess()
来自的位置(我猜是在猜想,但请纠正我并修改问题,如果这是错误的)。现在,您在此处生成 y 的预测值:
预测,MSE = GP.Predict(testx,eval_mse = true)
,但是,正如我们可以从
如果是这样,当您尝试将三个“列”放入单个数据框列中时,您将传递3个项目,只有1个适合。
In general, the error
ValueError: Wrong number of items passed 3, placement implies 1
suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equationresults['predictedY'] = predictedY
is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.
Here, it appears you are using sklearn for modeling, which is where
gaussian_process.GaussianProcess()
is coming from (I'm guessing, but correct me and revise the question if this is wrong).Now, you generate predicted values for y here:
predictedY, MSE = gp.predict(testX, eval_MSE = True)
However, as we can see from the documentation for GaussianProcess,
predict()
returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return(n_samples, n_targets)
which, depending ontestX
, could be(1000, 3)
(just to pick numbers). Thus, yourpredictedY
might have 3 columns.If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.