我遇到从字典中提取值的问题。我已经从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
答案 0 :(得分:2)
这使得字典具有第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}