Skip to main content
 首页 » 编程设计

python之字典列表中的百分位数

2024年10月24日10dflying

我在从字典中提取值时遇到问题。我从 CSV 文件创建了这本词典。但是,当我尝试为字典中的每个键提取百分位值时,我遇到了困难。我的字典看起来像这样:

dic = {'2008': [10,20, 56, 30, 57], '1950': [10.1,59.6, 56, 30.8, 99.6]}.  

我希望我的输出为:

1950,56.0
2008,30.0

到目前为止我尝试的是:

import numpy as np 
 
dic ={} 
 
pert ={'key':'value'} 
for k in dic.keys(): 
 
    for items in dic[k]: 
    p = np.percentile(items,95) 
    pert[k] = p 

请您参考如下方法:

这会生成一个包含第 95 个百分位数的字典:

dic = {'2008': [10,20, 56, 30, 57], '1950': [10.1,59.6, 56, 30.8, 99.6]} 
res = {k: np.percentile(v, 95) for k, v in dic.items()} 

res的内容:

{1950': 91.599999999999994, '2008': 56.799999999999997} 

获取中位数:

>>> {k: np.median(v) for k, v in dic.items()} 
{'1950': 56.0, '2008': 30.0}