mlenthusiast
mlenthusiast

Reputation: 1204

Using dict mapping instead of multiple if statements

I have a simple function that takes a weekday column and converts it into actual names of the days like so:

def convert_weekday(day):
    if day==0:
        return 'Mon'
    elif day==1:
        return 'Tue'
    elif day==2:
        return 'Wed'
    elif day==3:
        return 'Thu'
    elif day==4:
        return 'Fri'
    elif day==5:
        return 'Sat'
    elif day==6:
        return 'Sun'
    else:
        return day

df['day_of_week']=df['day_of_week'].apply(convert_weekday)

This works fine, but I would like to reduce the run time using dictionary mapping like this:

dict_days = {
    0: 'Mon',
    1: 'Tue',
    2: 'Wed',
    3: 'Thu',
    4: 'Fri',
    5: 'Sat',
    6: 'Sun'
}
def map_days(day):
    func = dict_days[day]
    func()

df['day_of_week']=df['day_of_week'].apply(map_days)

But this gives me an error TypeError: 'str' object is not callable. Any help resolving this would be appreciated.

Upvotes: 0

Views: 773

Answers (1)

rdas
rdas

Reputation: 21285

The map_days function is wrong. It's trying to invoke (i.e. ()) a string that's stored in the dictionary

In fact you don't need the function at all, you can just use the dictionary.get method.

dict_days = {
    0: 'Mon',
    1: 'Tue',
    2: 'Wed',
    3: 'Thu',
    4: 'Fri',
    5: 'Sat',
    6: 'Sun'
}

df['day_of_week']=df['day_of_week'].apply(dict_days.get)

Upvotes: 3

Related Questions