错误 **ValueError: 传递的项目数错误 2,位置暗示 1**

Posted

技术标签:

【中文标题】错误 **ValueError: 传递的项目数错误 2,位置暗示 1**【英文标题】:Error **ValueError: Wrong number of items passed 2, placement implies 1** 【发布时间】:2021-07-13 21:23:56 【问题描述】:

通过的项目数量错误 2,位置暗示 1 我想计算 AAMZN 和 AAPL 错误的“隔夜收益”和“盘中收益”

df['intradayReturn'] = (df1["adj_close"]/df1["open"])-1

df['overnightReturn'] = (df1["open_shift"]/df1["adj_close"])-1

在python中,下面是我的代码:

import numpy as np

import pandas as pd

import datetime 

import matplotlib.pyplot as plt


import warnings

df = yf.download(['AAPL','AMZN'],start='2006-01-01',end='2020-12-31')**

df.head()

Adj Close   Close   High    Low Open    Volume
AAPL    AMZN    AAPL    AMZN    AAPL    AMZN    AAPL    AMZN    AAPL    AMZN    AAPL    AMZN
Date                                                
2006-01-03  2.299533    47.580002   2.669643    47.580002   2.669643    47.849998   2.580357    46.250000   2.585000    47.470001   807234400   7582200
2006-01-04  2.306301    47.250000   2.677500    47.250000   2.713571    47.730000   2.660714    46.689999   2.683214    47.490002   619603600   7440900
2006-01-05  2.288151    47.650002   2.656429    47.650002   2.675000    48.200001   2.633929    47.110001   2.672500    47.160000   449422400   5417200
2006-01-06  2.347216    47.869999   2.725000    47.869999   2.739286    48.580002   2.662500    47.320000   2.687500    47.970001   704457600   6152900
2006-01-09  2.339525    47.080002   2.716071    47.080002   2.757143    47.099998   2.705000    46.400002   2.740357    46.549999   675040800   8943100**

到目前为止,它工作正常 但是当我使用这个公式时

df['intradayReturn'] = (df["Adj Close"]/df["Open"])-1


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'intradayReturn'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
   3824         try:
-> 3825             loc = self._info_axis.get_loc(key)
   3826         except KeyError:

~\Anaconda3\lib\site-packages\pandas\core\indexes\multi.py in get_loc(self, key, method)
   2875         if not isinstance(key, tuple):
-> 2876             loc = self._get_level_indexer(key, level=0)
   2877             return _maybe_to_slice(loc)

~\Anaconda3\lib\site-packages\pandas\core\indexes\multi.py in _get_level_indexer(self, key, level, indexer)
   3157 
-> 3158             idx = self._get_loc_single_level_index(level_index, key)
   3159 

~\Anaconda3\lib\site-packages\pandas\core\indexes\multi.py in _get_loc_single_level_index(self, level_index, key)
   2808         else:
-> 2809             return level_index.get_loc(key)
   2810 

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083 

KeyError: 'intradayReturn'

    enter code here

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-24-b2a4b46270a9> in <module>
----> 1 df['intradayReturn'] = (df["Adj Close"]/df["Open"])-1

~\Anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   3161         else:
   3162             # set column
-> 3163             self._set_item(key, value)
   3164 
   3165     def _setitem_slice(self, key: slice, value):

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   3238         self._ensure_valid_index(value)
   3239         value = self._sanitize_column(key, value)
-> 3240         NDFrame._set_item(self, key, value)
   3241 
   3242         # check if we are modifying a copy

~\Anaconda3\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
   3826         except KeyError:
   3827             # This item wasn't present, just insert at end
-> 3828             self._mgr.insert(len(self._info_axis), key, value)
   3829             return
   3830 

~\Anaconda3\lib\site-packages\pandas\core\internals\managers.py in insert(self, loc, item, value, allow_duplicates)
   1201             value = safe_reshape(value, (1,) + value.shape)
   1202 
-> 1203         block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
   1204 
   1205         for blkno, count in _fast_count_smallints(self.blknos[loc:]):

~\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in make_block(values, placement, klass, ndim, dtype)
   2730         values = DatetimeArray._simple_new(values, dtype=dtype)
   2731 
-> 2732     return klass(values, ndim=ndim, placement=placement)
   2733 
   2734 

~\Anaconda3\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
    141         if self._validate_ndim and self.ndim and len(self.mgr_locs) != len(self.values):
    142             raise ValueError(
--> 143                 f"Wrong number of items passed len(self.values), "
    144                 f"placement implies len(self.mgr_locs)"
    145             )

它显示这个错误 ValueError: 传递的项目数错误 2,位置意味着 1

【问题讨论】:

【参考方案1】:

这是 EZ PZ,您可以通过下面的代码轻松做到这一点。

gf = (df['Adj Close']['AAPL']/df['Open']['AAPL']-1).to_frame()
sd = (df['Adj Close']['AMZN']/df['Open']['AMZN']-1).to_frame()
df['intradayReturn', 'AAPL'] = gf
df['intradayReturn', 'AMZN'] = sd
df.head()

所以你的输出是这样的:

当涉及到多索引列时,您需要单独分配。

现在轮到你过夜返回了?。

【讨论】:

以上是关于错误 **ValueError: 传递的项目数错误 2,位置暗示 1**的主要内容,如果未能解决你的问题,请参考以下文章

Pandas DataFrame ValueError:传递的项目数错误 2,位置暗示 1

ValueError:传递值的形状为 (569, 30),索引暗示 (569, 31)

在 Pandas 上创建变量时出错 - 传递的项目数错误

出现错误:“ValueError:如果使用所有标量值,则必须传递索引”将 ndarray 转换为 pandas Dataframe

ValueError:熊猫数据框中的项目数量错误

ValueError:错误的项目数通过 3,位置暗示 1