Search code examples
pythonarraysdataframedictionarymode

Can't print month value from dictionary


I am trying to print the month name from this dictionary which is defined well before the code:

month_index = { '1': 'January',
                '2': 'February',
                '3': 'March',
                '4': 'April',
                '5': 'May',
                '6': 'June'}

I try to access the element using dataframe.mode() from some dataframe that outputs multiple columns one of which produces a month column where the values are only 1,2,3,4,5, or 6, representing January to June. dataframe.mode is producing 0 6 where 6 = June.

common_month = df['month'].mode()
        if common_month in month_index:
            print('The most common month is ', month_index, '.')

Should I create a dictionary with the results from .mode() or just use df['month'].mode().str[1] then use in to access value in the month_index? Any help would be appreicated.


Solution

  • The way you're doing it now, it is checking the dict keys for common_month, but you need to check the values. Also I'm assuming you want to print only the most common month, not the whole dictionary. Just change the if statement to this.

    if common_month in month_index.values():
                print(f'The most common month is {common_month}.')