【问题标题】:How to print 25th percentile to 75th percentile value of a dictionary?如何打印字典的第 25 个百分位到第 75 个百分位值?
【发布时间】:2019-08-23 02:59:47
【问题描述】:

我想打印从字典的第 25 个百分位点到第 75 个百分位点的所有值没有 numpy

这是我试过的代码sn-p。

# No Numpy allowed
import pandas as pd
def display_dashboard():
    df=pd.DataFrame({'student':student_list,'marks':marks_list})
    sorte=df.sort_values('marks',ascending=False)
    per_25=round(0.25*len(marks_list))
    per_75=round(0.75*len(marks_list))
    sor=df.sort_values('marks')
    new_dict = {k:v for k, v in sor.items() for v in range(per_25,per_75)}
    print("Students whose marks are between 25th % and 75th % are:-")
    print(new_dict)

它给出的答案是:-

Students whose marks are between 25th % and 75th % in ascending order of marks are:-
{'student': 7, 'marks': 7}

我想要一本字典,其中显示学生及其分数在字典总分的第 25 个百分位和第 75 个百分位之间。

【问题讨论】:

  • 你知道 pandas 需要 numpy 对吧?

标签: python python-3.x dictionary percentile


【解决方案1】:

您可以将zip学生列表和标记列表一起进行排序,并使用itertools.islice获取第25和第75个百分位数之间的迭代器,并将迭代器传递给dict构造函数以构建一个将学生姓名映射到他们的分数的字典:

from itertools import islice
from operator import itemgetter
student_list = ['Amy', 'Ben', 'Carl', 'Dan', 'Ean', 'Fab', 'Gal', 'Han']
marks_list = [29, 70, 55, 81, 13, 42, 84, 37]
total = len(marks_list)
print(dict(islice(sorted(zip(student_list, marks_list), key=itemgetter(1, 0), reverse=True), round(0.25 * total), round(0.75 * total))))

这个输出:

{'Ben': 70, 'Carl': 55, 'Fab': 42, 'Han': 37}

【讨论】:

    【解决方案2】:

    在你形成dict的for循环中,kstudentmarksv是索引。因此,在 dict 键中 ('studentandmarks) are overridden and the last index value7` 被保留。因此,您会得到结果:

    {'student': 7, 'marks': 7}
    

    我已将for loop 替换为filter,然后将DataFrame 转换为dict

    sor = sor.loc[(sor.index >= per_25) & (sor.index <= per_75)]
    new_dict = sor.to_dict('records')
    

    这是修改后的可执行代码:

    import pandas as pd
    
    student_list=['a', 'b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    marks_list=[18, 45, 50, 100, 34, 45, 87, 50, 90, 26]
    
    df=pd.DataFrame({'student':student_list,'marks':marks_list})
    sorte=df.sort_values('marks',ascending=False)
    per_25=round(0.25*len(marks_list))
    per_75=round(0.75*len(marks_list))
    sor=df.sort_values('marks')
    sor = sor.loc[(sor.index >= per_25) & (sor.index <= per_75)]
    new_dict = sor.to_dict('records')
    print("Students whose marks are between 25th % and 75th % are:-")
    print(new_dict)
    

    它产生输出:

    Students whose marks are between 25th % and 75th % are:-
    [{'student': 'e', 'marks': 34}, {'student': 'f', 'marks': 45}, {'student': 'c', 'marks': 50}, {'student': 'h', 'marks': 50}, 
    {'student': 'g', 'marks': 87}, {'student': 'i', 'marks': 90}, {'student': 'd', 'marks': 100}]
    

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2020-08-07
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 2012-11-03
      • 1970-01-01
      • 2019-01-06
      相关资源
      最近更新 更多