代码之家  ›  专栏  ›  技术社区  ›  SBad

索引器错误:单个位置索引器超出界限,并且是if条件

  •  1
  • SBad  · 技术社区  · 7 年前

    我有一个如下所示的数据框:

        Repo
        Out[624]: 
    
    1             Instrument    Term Code  WTD Rate
    2    GC_AUSTRIA_SUB_10YR          T-N     -0.49
    3    GC_AUSTRIA_SUB_10YR            O -0.467643
    4      R_RAGB_1.15_10/18          S-N -0.520299
    5      R_RAGB_4.35_03/19          S-N -0.497759
    6      R_RAGB_4.35_03/19          T-N      -0.5
    7      R_RAGB_1.95_06/19          S-N -0.501478
    8      R_RAGB_0.25_10/19          S-N -0.497765
    

    我有一个依赖于“仪器”列的if条件

    if condition:
       return Repo.loc[(Repo['Instrument']=='GC_LCH_BELGIUM') & (Repo['Term Code']=='T-N'),'WTD Rate'].iloc[0]
    

    问题是仪器名称有时不存在并得到一个错误 IndexError: single positional indexer is out-of-bounds

    我怎么能在“如果条件”中说,如果仪器确实存在(或者如果有错误),则返回到默认值say 10。

    我应该指出,当仪器不存在时,数据帧中没有行。因此,类似“is empty”的代码将不起作用

    3 回复  |  直到 7 年前
        1
  •  2
  •   jezrael    7 年前

    我认为问题是过滤返回为空 DataFrame ,因此不可能选择第一个值并引发错误。

    所以需要检查一下 empty 具有 if-else :

    if condition:
       a =  Repo.loc[(Repo['Instrument']=='GC_LCH_BELGIUM')&(Repo['Term Code']=='T-N'),'WTD Rate']
       return 'empty' if a.empty else a.iloc[0]
    
        2
  •  2
  •   Bharath M Shetty    7 年前

    因为访问器中的条件有可能不满足,所以您可以一直选择 try except

    if condition :
        try:
           return Repo.loc[(Repo['Instrument']=='GC_LCH_BELGIUM')&(Repo['Term Code']=='T-N'),'WTD Rate'].iloc[0]
        except IndexError:
           return 10
    
        3
  •  2
  •   jpp    7 年前

    你可以用 next 并提供 10 :

    if condition:
        mask = (Repo['Instrument']=='GC_LCH_BELGIUM') & (Repo['Term Code']=='T-N')
        s = Repo.loc[mask, 'WTD']
        return next(iter(s), 10)
    

    在内部,通过 StopIteration 序列为空并还原为默认值时出错。