繁体   English   中英

使用熊猫数据框中的不同参考行比较数值

[英]Compare numerical values using different reference rows in pandas data frame

我有一项作业,要求我根据在每个具有参考分数的课程中选拔一名或多名参考学生,计算几班学生的分数差异是否高于0.2。

这是示例数据帧

df = pd.DataFrame({'student' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
     'class' : [1, 1, 1, 2, 2, 2, 2, 2, 2, 2],
     'type' : ['top', 'top', 'low', 'mid', 'mid', 'mid', 'low', 'low', 'low', 'low'],
     'score' : [1, .8, .3, .7, .7, .6, .1, .2, .1, .1]})
df

该算法应包含以下规则

  1. 选择参考学生时,首先要优先考虑“顶尖”学生,然后是“中等”表现学生,并在有多个候选人的情况下检查谁更接近基数0.5(在“第1类”的示例中,我们有两个“顶尖”学生,但我们选择0.8接近0.5的第二个,在“ 2级”中,我们选择0.6的“中级”学生比0.7的学生更接近0.5,并且我们没有“顶级”学生)
  2. 计算每个非参照学生得分与参照的差异,如果差异> 0.2,则写'yes',如果差异<= 0.2,则写'no'。

所以最终结果将是

df2 = pd.DataFrame({'student' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
     'class' : [1, 1, 1, 2, 2, 2, 2, 2, 2, 2],
     'type' : ['top', 'top', 'low', 'mid', 'mid', 'mid', 'low', 'low', 'low', 'low'],
     'score' : [1, .8, .3, .7, .6, .6, .1, .2, .1, .1],
     'outcome' : ['no', 'ref', 'yes', 'no', 'ref', 'ref', 'yes', 'yes', 'yes', 'yes']})
df2

我对熊猫有一些基本的了解,但我认为这个问题对我来说太复杂了。 您对此有任何想法吗?

def final_output(df):
    # groups class & type
    groups = df2.groupby(['class', 'type'])

    # cl will have key as 'Class' & value as 'reference student score' 
    cl = {}
    for name,group in groups:
        if 'top' in name[1]:
            cl[name[0]] = group['score'].min()
        elif 'mid' in name[1]:
            cl[name[0]] = group['score'].min()

    # Assigning reference student score to their respective class students
    df['refer_score'] = df['class'].apply(lambda x: cl[x])
    # difference being reference student score minus actual score of the student
    df['diff'] = df.apply(lambda x: abs(x['refer_score'] - x['score']), axis=1)

    df['final_outcome'] = df['diff'].apply(lambda x: 'yes' if x > 0.2 else 'ref' if x == 0.0 else 'no')
    return df

output = final_output(df2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM