【问题标题】:I have to find the mode for a column. There is issue when the mode is same for two values and python is returning me in alphabetical order我必须找到列的模式。当两个值的模式相同并且python按字母顺序返回我时会出现问题
【发布时间】:2021-12-23 19:37:48
【问题描述】:

我有以下数据。

    #   Priority
0   1   Low
1   2   Low
2   3   Medium
3   4   Medium
4   5   Critical
5   6   Low
6   7   Medium
7   8   High
8   9   Critical
9   10  Low
10  11  Medium
11  12  High

我有分数的键值对,例如,

score_by_priority_category = dict()
score_by_priority_category['Critical'] = 1
score_by_priority_category['High'] = 0.6
score_by_priority_category['Medium'] = 0.4
score_by_priority_category['Low'] = 0.2

当我发现“优先级”列的模式时,它给了我“低”,但我想要“中”,因为它的分数更高。

vc = df['Priority'].value_counts()
candidate_mode_value=list(df['Priority'].mode().to_dict().values())[0]

在上述情况下,返回的候选模式值是“低”。当有多个相同模式的值时,如何获取得分更高的值。

【问题讨论】:

    标签: python dataframe statistics mode


    【解决方案1】:

    使用内置max函数的关键参数:

    counts = df["Priority"].value_counts().to_dict()
    res = max(counts, key=lambda x: (counts[x], score_by_priority_category[x]))
    print(res)
    

    输出

    Medium
    

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2012-05-30
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      相关资源
      最近更新 更多