SBad
SBad

Reputation: 1345

IndexError: single positional indexer is out-of-bounds and if condition

I have a dataframe that looks like this:

    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

I have an if condition which is dependent on the column "Instrument"

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

The issue is that the Instrument name sometimes does not exist and get an error IndexError: single positional indexer is out-of-bounds

How can I say in the "if condition" that if the instrument does exist (or if there is an error) reverts back to default value of say 10.

I should point out that when Instrument does not exist there is no row in the dataframe. therefore code that looks something like "is empty" would not work

Upvotes: 1

Views: 3114

Answers (3)

jpp
jpp

Reputation: 164623

You can use next and supply a default argument of 10:

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

Internally, this works by raising a StopIteration error when the series is empty and reverting to the default value.

Upvotes: 2

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Since there are chances that condition inside the accessor is not met you can always go for try and except i.e

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

Upvotes: 2

jezrael
jezrael

Reputation: 862481

I think problem is filtering return empty DataFrame, so not possible select first value and error is raised.

So need check if empty with 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]

Upvotes: 2

Related Questions