我有一个作业,要求我基于在每个具有参考分数的班级中选拔一名或多名参考学生来计算几班学生的分数差是否高于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
该算法应包含以下规则
所以最终结果将是
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
我对熊猫有一些基本了解,但我认为这个问题对我来说太复杂了。您对此有任何想法吗?
答案 0 :(得分:1)
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)