【发布时间】:2015-01-08 23:06:04
【问题描述】:
将 IPython (Python 3.4) 与 pandas 一起使用:我有一个大致如下所示的数据框(注意每个学生的重复记录,有时每个学生有 3 个以上的记录):
Year Subject Student Score Date
2014 Math 1 34 31-Jan
2014 Math 1 34 26-Jan
2014 Math 2 65 26-Jan
2014 Math 2 76 31-Jan
2014 Math 3 45 3-Feb
2014 Math 3 67 31-Jan
我正在寻找一种方法来根据以下标准返回每个学生的分数: 1.最高分 当每个学生记录的分数相同时: 2. 最近日期
这是所需的输出:
Year Subject Student Score Date
2014 Math 1 34 31-Jan
2014 Math 2 76 31-Jan
2014 Math 3 67 31-Jan
这是我迄今为止尝试过的: 在年份、学科和学生上使用 groupby 以获得给定年份和学科领域每个学生的最高分:
by_duplicate = df.groupby(['Year', 'Subject', 'Student'])
HighScore = by_duplicate[['Year', 'Subject', 'Student', 'Score']].max()
在这里,我重命名了 score 列,以便当我将它加入到原始数据框时,我知道哪一列是哪一列。这可能没有必要,但我不确定。
HighScore.rename(columns={'Score': 'Score2'}, inplace=True)
在这里,我添加了一个空白的“HighScore”列,以期如果该行具有最高分,稍后将填充 1。稍后会详细介绍...
HighScore['HighScore'] = ""
然后我对最近的日期做同样的事情:
Recent = by_duplicate[['Year', 'Subject', 'Student', 'Date']].max()
Recent.rename(columns={'Date': 'Date2'}, inplace=True)
Recent['Recent'] = ""
My approach was to
1. create tables for each field (score and date) using groupby,
2. identify the rows containing the highest and most recent scores, respectively, by entering a "1" in their respective new columns (HighScore' and 'Recent')
3. somehow join these grouped tables back to the original dataframe on Year, Subject, and Student
-I'm guessing this requires somehow ungrouping the groups as the pd.merge is not working on the grouped data frames
4. The end result, according to my theory, would look something like this:
Year Subject Student Score Date HighScore Recent
2014 Math 1 34 31-Jan 1 1
2014 Math 1 34 26-Jan 1 0
2014 Math 2 65 26-Jan 0 0
2014 Math 2 76 31-Jan 1 1
2014 Math 3 45 3-Feb 0 1
2014 Math 3 67 31-Jan 1 0
And once I have this table, I would need to do something like this:
1. Per student for a given year and subject area: return the sum of 'HighScore'
2. If the sum of 'HighScore' is greater than 1, then take the 'Recent' row equal to 1.
I believe this will give me what I need.
提前致谢!!!
【问题讨论】: