How to pre-process month abbreviation for modelling

Viewed 28

Given the below column:

col
0 NaN
1 Jan,Apr,Jul,Oct
2 Jan,Jun,Jul
3 Apr,May,Oct,Nov
4 NaN

How to convert the month abbreviation into integer data that can be fed to the model?

1 Answers

Would this be on the right path for you? The function is just a look up of the value in a Python dictionary and returns the value if found or None if not.

You can then split the column in each row to get a list of the months. It's not entirely clear if that's what's required as there is no desired output provided.

    def month_to_int(abbreviated_month):
        return {
                'Jan': 1,
                'Feb': 2,
                'Mar': 3,
                'Apr': 4,
                'may': 5,
                'Jun': 6,
                'Jul': 7,
                'Aug': 8,
                'Sep': 9, 
                'Oct': 10,
                'Nov': 11,
                'Dec': 12
        }.get(abbreviated_month)
    
    rows = [
        'NaN',
        'Jan,Apr,Jul,Oct',
        'Jan,Jun,Jul',
        'Apr,May,Oct,Nov',
        'NaN'
    ]
    
    for row in rows:
        print([month_to_int(month) for month in row.split(',')])


    [None]
    [1, 4, 7, 10]
    [1, 6, 7]
    [4, None, 10, 11]
    [None]
Related