我有一个如下所示的数据框:
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条件取决于“Instrument”列
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
如何在“if condition”中说如果仪器确实存在(或者如果有错误)则恢复为默认值10。
我应该指出,当Instrument不存在时,数据帧中没有行。因此看起来像“空”的代码不起作用
答案 0 :(得分:2)
我认为问题是过滤返回空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]
答案 1 :(得分:2)
您可以使用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
错误。
答案 2 :(得分:2)
由于有可能无法满足访问者内部的条件,因此您可以始终选择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