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

Viewed 54

I have following data.

    #   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

I am having scores' key value pair like,

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

When I am finding out the Mode of the "Priority" column, it is giving me as 'Low' but I want the 'Medium' as it is having more score.

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

In above case, candidate_mode_value returned is 'Low'. How to get the value which is having more score when there are multiple values with same mode.

1 Answers

Use the key parameter of the built-in max function:

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

Output

Medium
Related