python - 按 ID 分组,选择同一 ID 列中的最高值

标签 python pandas pandas-groupby

我在尝试计算一些期末考试分数时遇到问题。我需要按学生分组,只获取每个学生每列中的最高值。

作为 DF 数据框:

data = {'Students': ['Student1', 'Student1', 'Student1', 'Student2','Student2','Studen3'], 
        'Result1': [2, 4, 5, 8, 2, 5],
        'Result2': [5, 3, 2, 8, 5, 5],
        'Result3': [7, 5, 7, 3, 8, 9]}
df = pd.DataFrame(data)

    Students    Result1     Result2     Result3
0   Student1    2   5   7
1   Student1    4   3   5
2   Student1    5   2   7
3   Student2    8   8   3
4   Student2    2   5   8
5   Studen3     5   5   9

我需要生成一个 DF,在每个结果中为每个学生选择较高的分数。

所以,最终的 DF 应该是这样的:

    Students    Result1     Result2     Result3
0   Student1    5   5   7
1   Student2    8   8   8
2   Student3    5   5   9

有什么帮助吗?

最佳答案

可以使用简单的组迭代来生成数据框:

df2 = pd.DataFrame(columns=('Student', 'res1', 'res2', 'res3'))

for s in df.Students.unique():
    stdf = df[df["Students"]==s]
    df2 = df2.append({'Student':s,'res1':max(stdf.Result1),'res2':max(stdf.Result2),
                      'res3':max(stdf.Result3)}, ignore_index=True)

关于python - 按 ID 分组,选择同一 ID 列中的最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70086045/

相关文章:

python - 如何从该列中仅提取数字?

python - 使用 python pandas 将 csv 文件中的多行合并为一行

python - pandas如何检查每组中列值之间的差异是否在范围内

pandas - 如何在 Pandas 中按不同 DF 的日期时间范围进行分组

python - 如何知道 optparse 选项是在命令行中传递的还是作为默认选项传递的

python - 对象相似性 Pandas 和 Scikit Learn

python - 如何使用Python运行外部可执行文件?

python - Windows/Python pygame.错误 : video system not initialized after adding Mp3 file

python - Pandas : how to merge 2 dataframes on key1. str.endswith(key2)

python-3.x - Pandas 分配列值取决于 df 中的另一列