![](/img/trans.png)
[英]How to iterate over column values for unique rows of a data frame with sorted, numerical index with duplicates in pandas?
[英]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
該算法應包含以下規則
所以最終結果將是
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.