ValueError: Wrong number of items passed - Meaning and suggestions?

ValueError: Wrong number of items passed - Meaning and suggestions?

我收到错误消息: ValueError: Wrong number of items passed 3, placement implies 1,我正在努力弄清楚从哪里开始解决这个问题,以及如何开始解决这个问题。

我不太明白错误的意思;这让我很难排除故障。我还在我的 Jupyter Notebook 中包含了触发错误的代码块。

数据难以附加;所以我不希望任何人尝试为我重新创建此错误。我只是在寻找有关如何解决此错误的反馈。

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

一般来说,错误 ValueError: Wrong number of items passed 3, placement implies 1 表明您试图将太多的鸽子放入太少的鸽笼中。在这种情况下,等式右边的值

results['predictedY'] = predictedY

正试图将 3 个 "things" 放入一个只允许一个的容器中。因为左侧是数据框列,并且可以在该(列)维度上接受多个项目,所以您应该看到另一个维度上的项目太多。

在这里,您似乎正在使用 sklearn 进行建模,这就是 gaussian_process.GaussianProcess() 的来源(我猜,但如果这是错误的,请纠正我并修改问题)。

现在,您在此处生成 y 的预测值:

predictedY, MSE = gp.predict(testX, eval_MSE = True)

但是,从the documentation for GaussianProcesspredict()、return的两项可以看出。第一个是 y,它是 array-like(强调我的)。这意味着它可以有不止一个维度,或者,对于像我这样头脑笨的人来说,具体来说,它可以有不止一列——看它可以 return (n_samples, n_targets) 这取决于testX,可能是 (1000, 3)(只是为了挑选数字)。因此,您的 predictedY 可能有 3 列。

如果是这样,当您尝试将具有三个 "columns" 的内容放入单个数据框列时,您将传递 3 个项目,而只有 1 个适合。

不确定这是否与您的问题相关,但将来可能与其他人相关:我遇到了类似的错误。原来 df 是空的(有零行),这就是导致我的命令出错的原因。

for i in range(100):
try:
  #Your code here
  break
except:
  continue

这个对我有用。

因此 ValueError:传递的项目数量错误 3,放置意味着 1 发生在您传递给许多参数但方法仅支持少数参数时。例如 -

df['First_Name', 'Last_Name'] = df['Full_col'].str.split(' ', expand = True)

在上面的代码中,我试图将 Full_col 分成两个子列名称 -First_Name 和 Last_Name,所以这里我会得到错误,因为相反列列表我只传递一个参数的列。

所以为了避免这种情况 - 使用另一个子列表

df[['First_Name', 'Last_Name']] = df['Full_col'].str.split(' ', expand = True)

此错误的另一个原因是当您在 DataFrame 上应用一个函数时,其中有两个同名的列。

只需将其添加为答案:嵌套方法和错放右括号也会引发此错误,例如:

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)

与(正确的)版本: 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))

这对你们大多数人来说可能是常识,但我很困惑,直到我意识到我的错误。

从 pandas 1.3.x 开始不允许将对象(例如来自嵌入的 eagertensor)填充到列中。

https://github.com/pandas-dev/pandas/blame/master/pandas/core/internals/blocks.py

我在尝试将单列数据帧 df 转换为系列 pd.Series(df) 时遇到此错误。 我用

解决了这个问题
pd.Series(df.values.flatten())

问题是数据框中的值是列表:

  my_col
0 ['a']
1 ['b']
2 ['c']
3 ['d']

当我打印数据框时,它没有显示括号,这使得很难找到。