在字典中查找最大值,并将所有值除以此值

时间:2017-10-26 15:44:10

标签: python pandas

我有一把包含100把钥匙的字典。它看起来像这样:

{'key1': [0.0, 0.0, 0.95, 0.06, 0.01],'key2': [0.0, 0.1, 0.95,
0.26, 0.11].....'key100': [0.2, 0.0, 0.23, 0.16, 0.21]}

我希望找到最大值(在上面的示例中它将是0.95)并将所有键的所有值除以此值。基本上我会将字典转换为最大值的百分比。如果有人能告诉我如何在pandas / python中做到这一点,我将非常感激。

谢谢。

6 个答案:

答案 0 :(得分:2)

试试这个:

# First, find the global maximum value
max_val = 0.0
for key, value_list in d.iteritems():
    local_max = max(value_list)
    if local_max > max_val:
        max_val = local_max

# Then divide every item in every value list by the global maximum
new_dict = {}
for key, value_list in d.iteritems():
    new_dict[key] = [x/max_val for x in value_list]

答案 1 :(得分:2)

以下是如何使用pandas做到这一点。

import pandas as pd

data = {'key1': [0.0, 0.0, 0.95, 0.06, 0.01],'key2': [0.0, 0.1, 0.95,
0.26, 0.11], 'key100': [0.2, 0.0, 0.23, 0.16, 0.21]}

df = pd.DataFrame(data)

max_value = df.max().max()

df /= max_value

答案 2 :(得分:1)

快速写作但是"哑巴"如果我们遇到更高的值,那就是走dict并更新sentinel值:

maxval = 0.0
for key in d:
    for val in d[key]:
        if val > maxval:
            maxval = val


for key in d:
    d[key] = [val / maxval for val in d[key]]

答案 3 :(得分:1)

d = {'key1':......}
from itertools import chain
max_val = max(chain.from_iterable(d.values()))
{k:[i/max_val for i in v] for k,v in d.items()}

答案 4 :(得分:1)

尝试以下代码:

import pandas as pd
data = {'key1': [0.0, 0.0, 0.95, 0.06, 0.01],'key2': [0.0, 0.1, 0.95,
0.26, 0.11], 'key100': [0.2, 0.0, 0.23, 0.16, 0.21]}
data = pd.DataFrame(data)
max_value = data.max().unique()
data = data.divide(max_value[0])

答案 5 :(得分:0)

试试这个:

data = {'key1': [0.0, 0.0, 0.95, 0.06, 0.01],
        'key2': [0.0, 0.1, 0.95, 0.26, 0.11],
        'key100': [0.2, 0.0, 0.23, 0.16, 0.21]}
max_in_data = max(max(vals) for vals in data.values())
data = {key: map(lambda x: x/max_in_data, vals) 
        for key, vals in data.items()}