无法从字典中打印月份值

我正在尝试从这本字典中打印月份名称,该字典在代码之前定义得很好:


month_index = { '1': 'January',

                '2': 'February',

                '3': 'March',

                '4': 'April',

                '5': 'May',

                '6': 'June'}

我尝试使用dataframe.mode()某些输出多列的数据框访问元素,其中一列生成月份列,其中值仅为 1、2、3、4、5 或 6,代表一月到六月。dataframe.mode正在生产0    66 = 六月。


common_month = df['month'].mode()

        if common_month in month_index:

            print('The most common month is ', month_index, '.')

我应该用结果创建一个字典.mode()还是只使用df['month'].mode().str[1]然后使用in来访问 month_index 中的值?任何帮助将不胜感激。


陪伴而非守候
浏览 134回答 2
2回答

撒科打诨

你现在这样做的方式是检查 的字典键common_month,但你需要检查值。另外我假设你只想打印最常见的月份,而不是整个字典。只需将 if 语句更改为此即可。if common_month in month_index.values():             print(f'The most common month is {common_month}.')

慕斯王

mode() 函数将returning object pandas.core.series.Series数据类型。而且您没有检查字典值。所以你必须在 common_month 中使用 any/all,获取索引,并检查 dict 中的值。if common_month.any() in month_index.values():     print('The most common month is', common_month[0], '.')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python