Skip to main content
 首页 » 编程设计

python之索引错误 : single positional indexer is out-of-bounds and if condition

2025年05月04日15zhengyun_ustc

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

    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 

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

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

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

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

我应该指出,当 Instrument 不存在时,数据框中就没有行。因此看起来像“是空的”的代码将不起作用

请您参考如下方法:

我认为问题在于过滤返回空 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]