【问题标题】:Can't print month value from dictionary无法从字典中打印月份值
【发布时间】:2020-09-29 09:47:20
【问题描述】:

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

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

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

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 中的值?任何帮助将不胜感激。

【问题讨论】:

    标签: python arrays dataframe dictionary mode


    【解决方案1】:

    您现在的操作方式是检查 common_month 的字典键,但您需要检查值。另外我假设您只想打印最常见的月份,而不是整个字典。只需将 if 语句更改为此。

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

    【讨论】:

    • 它没有打印值。数据框不是month_index。我指的是另一个数据框,其中dataframe.mode() 正在大量输出``` 6```(即六月)但不打印
    • 一旦我调整了我希望我的common_month 相等的值,它就起作用了。相反,common_month = df['month'].mode()[0] if common_month in month_index: print('\nThe most common month is', month_index[common_month])
    • 如果您添加例如 common_month = df['month'].mode() 的输出,将来会有所帮助,因为我们不知道您的数据框是什么样的,因此更容易理解您的需求。跨度>
    • 我会的。如果不清楚,我深表歉意。我过去提出的问题提供了太多信息,所以我仍在学习如何正确格式化和提问。感谢您的建议。
    【解决方案2】:

    mode() 函数将 returning object pandas.core.series.Series 数据类型。而且您没有检查 dict 值。所以你必须在 common_month 中使用 any/all,获取索引,并检查 dict 中的值。

    if common_month.any() in month_index.values():
        print('The most common month is', common_month[0], '.')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多