Home > front end >  Handing error "index 0 is out of bounds for axis 0 with size 0" within a function
Handing error "index 0 is out of bounds for axis 0 with size 0" within a function

Time:12-15

df1 = pd.DataFrame({'name':['Sara',  'John', 'Christine'],

                   'email': ['[email protected]', '[email protected]', '[email protected]'],
                   'Country': ['US', 'US', 'UK'],
                   'Age': [25, 18, 33],
                   'Grade': ['High', 'Medium', 'Low']})

df1

Gives:

    name       email                  Country   Age Grade
0   Sara      [email protected]            US    25  High
1   John      [email protected]            US    18  Medium
2   Christine   [email protected]     UK    33  Low

What I am trying to do is searching within the df1 with certain criteria to find the country but I got this error returned from the function if values are not in the df1:

def getcon(name, Grade):
    con = df1.loc[(df1['name'] == name) & (df1['Grade'] == Grade), 'Country'].values[0]

If non existing name or grade passed to the function this will throw:

IndexError: index 0 is out of bounds for axis 0 with size 0

I tried to return none if the con is not true but I did not work:

def getcon(name, Grade):
    con = df1.loc[(df1['name'] == name) & (df1['Grade'] == Grade), 'Country'].values[0]
    if con is True:
        return con
    else:
        return None

How can I avoid this error if non existing values passed to the getcon function.

CodePudding user response:

I would do something like this:

def getcon(name, Grade):
    con = df1.loc[(df1['name'] == name) & (df1['Grade'] == Grade), 'Country']

    return con.iloc[0] if len(con) else None
  • Related