【问题标题】:python index out of bounds errorpython索引越界错误
【发布时间】:2014-01-27 01:25:35
【问题描述】:

试试这个代码:

f2 = []
for i in symb_list: 
    f2.append(earnings_vola(i))

给出索引超出范围错误。 symb_list 示例:

symb_list
Out[143]:
['MTMC',
 'ANCI',
 'TPLM',
 'BERK',
 'DGI',
 'QLTY',
 'GST',
 'AGEN',
 'NURO',

earnings_vola(i) 返回浮点数

UPD。对不起,我是新用户。

def earnings_vola (symbol):
    price_b = marketdata.ext.load_metotron('%s'%symbol)
    price = price_b.sort()
    d = pickle.load(open('/home/mad/Appr/data_%s.pickle'%(symbol), 'rb'))
    df = h.to_df(d)
    if df['timetype'][2]=='After Close':
        price['VOLA'] = (price.shift(-1)['C']-price['C'])/price['C']*100
    else:
        price['VOLA'] = (price['C']-price.shift(+1)['C'])/price['C']*100
    x1 = pa.Series(sorted(df['Date_p']))
    px = price.reindex(x1, method='ffill')
    avg_vola = np.mean(px['VOLA'])
    return avg_vola

UPD2

> IndexError                                Traceback (most recent call
> last) <ipython-input-144-f3de6042c223> in <module>()
>       1 f2 = []
>       2 for i in symb_list:
> ----> 3     f2.append(earnings_vola(i))
> 
> <ipython-input-123-96f164ec1ad9> in earnings_vola(symbol)
>       4     d = pickle.load(open('/home/mad/Appr/data_%s.pickle'%(symbol), 'rb'))
>       5     df = h.to_df(d)
> ----> 6     if df['timetype'][2]=='After Close':
>       7         price['VOLA'] = (price.shift(-1)['C']-price['C'])/price['C']*100
>       8     else:
> 
> /usr/local/lib/python2.7/dist-packages/pandas/core/series.pyc in
> __getitem__(self, key)
>     616     def __getitem__(self, key):
>     617         try:
> --> 618             return self.index.get_value(self, key)
>     619         except InvalidIndexError:
>     620             pass
> 
> /usr/local/lib/python2.7/dist-packages/pandas/core/index.pyc in
> get_value(self, series, key)
>     728 
>     729             try:
> --> 730                 return tslib.get_value_box(series, key)
>     731             except IndexError:
>     732                 raise
> 
> /usr/local/lib/python2.7/dist-packages/pandas/tslib.so in
> pandas.tslib.get_value_box (pandas/tslib.c:8534)()
> 
> /usr/local/lib/python2.7/dist-packages/pandas/tslib.so in
> pandas.tslib.get_value_box (pandas/tslib.c:8378)()
> 
> IndexError: index out of bounds

**UPD3 结果收益_vola(symbol)函数示例:

earnings_vola(symbol='MSFT')
0.080011249349832989**

我需要迭代符号列表(上面的示例)并在列表中获取所有结果

【问题讨论】:

  • 什么是earnings_vola
  • 抛出异常的是earnings_vola(i)。该函数中有什么,完整回溯是什么。
  • 请注意 Python 会抛出 IndexError 用于列表,而不是 index out of bounds.. 这让我非常好奇 earning_vola() 可能是什么..
  • 请在这里写下你的完整代码。 earing_vola 是什么?
  • 请提供实际的回溯以及实际的代码。几乎可以肯定,该异常来自该 earnings_vola 函数内部的某些代码,或者该函数调用的其他代码。回溯会告诉你(或者至少告诉我们,如果你不明白的话)它发生在哪个函数的哪一行。然后,如果你已经向我们展示了相关代码,我们就可以开始调试它了。

标签: python list pandas


【解决方案1】:

问题出在这一行:

if df['timetype'][2]=='After Close':

它抱怨df['timetype'] 是一个只有 0、1 或 2 个项目的序列,但你要的是第三个。

这可能是我们都犯的那种愚蠢的错字,你不小心写了2而不是1,或者忘记了Python序列使用从0开始的索引。

但如果不是,如果您真的希望 df['timetype'] 有 3 个或更多值而它没有,我们需要知道您希望它有什么值,为什么,以及它实际上是什么值 有。

您只需在代码中添加一行并再次运行即可开始调试:

    df = h.to_df(d)
    print(df['timetype']) # NEW CODE
    if df['timetype'][2]=='After Close':

如果结果不符合您的预期,请尝试打印出df 本身,或dh 等,直到找到第一个出错的地方。

在某些时候,您会发现第一步返回的值与您预期的不同。你可能仍然不知道为什么它会返回一个不同的值——但在这一点上,StackOverflow 有一个更容易回答的问题。

【讨论】:

  • @DSM:但这会返回KeyError,而不是IndexError,不是吗?当你有一个隐式索引时,你只会得到一个IndexError,对吧?或者有没有办法获得类似于稀疏隐式索引的东西,可以引发IndexError 用于索引到间隙?
  • 你知道,你是对的,那是KeyError,所以这个理论已经死了。回溯有点难以阅读——price 行有错误吗?
  • @DSM:是df['timetype'][2]。现在格式已修复,您可以看到它经过的调用链。但我不确切知道tslib.get_value_box 是如何工作的,我不想在不了解OP 期望df['timetype'] 持有什么或它实际持有什么的情况下深入研究源代码,因为我不知道认为它足够有启发性,值得付出努力。
【解决方案2】:

更改此代码

if df['timetype'][2]=='After Close':
    price['VOLA'] = (price.shift(-1)['C']-price['C'])/price['C']*100

到此代码(明确、正确和可读)

key = 'timetype'
value = df[key] if df and key in df else None
kw = value[2] if value and len(value) > 2 and value[2]=='After Close' else None
if kw:
    price['VOLA'] = (price.shift(-1)['C']-price['C'])/price['C']*100

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 2014-06-06
    • 2015-03-22
    • 2013-10-13
    • 2015-01-10
    • 2017-03-23
    • 2015-02-04
    相关资源
    最近更新 更多