Error while transforming series with series.map() function

Viewed 30
def locate (code):
    string1 = str(code)
    floor = string1[3]
    if floor == '1':
        return 'Ground Floor'
    else:
        if int(string1[5]) < 1:
            lobby = 'G'
        elif int(string1[5]) < 2:
            lobby = 'F'
        else:
            lobby = 'E'
        return floor + lobby
    
    
print(locate('S191009'))
print(locate('S087525'))

This function works fine with individual input code as above with Output

Ground Floor 7E

But when I use this to map a series in data frame, it shows error.

error_data1['location'] = error_data1['status'].map(locate)

Error message: string index out of range.

How can I fix this??

2 Answers

Your problem is with your series values:

se = pd.Series(['S191009', 'rt'])
se.map(locate)

produces the same error you reported. You can ignore these rows using try...except in function if it does not hurt you.

The problem is you are indexing an index on a string that doesn't exist (i.e the string is shorter than what you expect). As the other answer mentioned, if you try and use

my_string="foo"
print(my_string[5])

You will get the same error. To solve this you should add a try except statement, or for simplicity an initial if statement that returns "NotValid" or something like that. Your data probably has strings that do not follow the standard form you expect.

Related