首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >熊猫数据框架中使用不同参考行的数值比较

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

Stack Overflow用户
提问于 2018-08-09 11:42:57
回答 1查看 62关注 0票数 0

我有一项作业,要求我计算几个班级学生的分数是否高于0.2,这是基于在每个有参考分数的班级中挑选一个或多个参考学生。

下面是数据框架示例

代码语言:javascript
复制
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,以防出现多名考生(在“一班”的例子中,我们有两名“优秀”学生,但第二名的成绩接近于0.5,而在“二班”中,我们选择了0.6的“中”学生,比0.7的学生更接近0.5,而我们没有任何“优秀”学生)
  2. 用参考值计算每个非参考学生分数的差异,如果差异>0.2,则写“是”,如果有差异,则写“no”。

所以最终的结果是

代码语言:javascript
复制
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

我对熊猫有一些基本知识,但我认为这个问题对我来说太复杂了。你对如何做这件事有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2018-08-09 12:55:54

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51766103

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档