gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:54:32 25 4
gpt4 key购买 nike

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

    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]

关于python - 索引错误 : single positional indexer is out-of-bounds and if condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50623430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com