【问题标题】:Get value with max count from each key with multiple values Python dictionary从具有多个值 Python 字典的每个键中获取具有最大计数的值
【发布时间】:2020-04-26 23:04:43
【问题描述】:

我有一本字典,如下所示:

{
    'max_depth': [15, 20, 35, 20, 20],
    'min_samples_split': [1, 5, 5, 3, 2],
    'n_estimators': [50, 50, 50, 10, 10]
}

我想返回以下值,其中值是最常出现的值:

{
    'max_depth': 20,
    'min_samples_split': 5,
    'n_estimators': 50
}

我尝试了以下方法:

def most_freq_param(param_data_col):
    out = []

    #model params
    param_list = list(ast.literal_eval(param_data_col.iloc[1]).keys())

    params = {}
    max_params = {}     

    for i in range(len(param_list)): #create empty dict of params
        params[param_list[i]] = []
        max_params[param_list[i]] = []

    for i in range(len(param_data_col)):
        out.append(ast.literal_eval(param_data_col.iloc[i]))

    for value in out:
        for param in params:
            for i in range(len(param_list)):
                params[param].append(value[param_list[i]])

    for param in max_params:
        lst = params.get(param)
        max_value = max(lst,key=lst.count)
        max_params[param].append(max_value)

    return max_params

【问题讨论】:

标签: python list dictionary


【解决方案1】:

对于给定的字典, 参数 = {'max_depth':[15,20,35,20,20],'min_samples_split':[1,5,5,3,2],'n_estimators':[50,50,50,10,10] }

使用以下代码,您可以获得所需的输出:{'max_depth': 20, 'min_samples_split': 5, 'n_estimators': 50}

from statistics import mode
d = {'max_depth': [15,20,35,20,20], 'min_samples_split': [1,5,5,3,2], 'n_estimators': [50,50,50,10,10]}
max_params = {}
for key, value in d.items():
    max_params[key] = mode(d[key])

你也可以使用收集模块:

from collections import Counter
d = {'max_depth': [15,20,35,20,20], 'min_samples_split': [1,5,5,3,2], 'n_estimators': [50,50,50,10,10]}
max_params = {}
for key, value in d.items():
    max_params[key] = Counter(d[key]).most_common(1)[0][0]

详细了解收藏:https://docs.python.org/2/library/collections.html

现在您可以在函数中使用上述任何代码块来获取最频繁的参数

【讨论】:

    猜你喜欢
    • 2012-04-14
    • 2011-06-09
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多