【发布时间】:2018-05-11 01:37:02
【问题描述】:
假设我有一个学生考试成绩的数据框,其中每个学生学习不同的科目。每个学生可以多次参加每个科目的考试,只保留最高分(满分 100 分)。例如,假设我有一个包含所有测试记录的数据框:
| student_name | subject | test_number | score |
|--------------|---------|-------------|-------|
| sarah | maths | test1 | 78 |
| sarah | maths | test2 | 71 |
| sarah | maths | test3 | 83 |
| sarah | physics | test1 | 91 |
| sarah | physics | test2 | 97 |
| sarah | history | test1 | 83 |
| sarah | history | test2 | 87 |
| joan | maths | test1 | 83 |
| joan | maths | test2 | 88 |
(1) 如何只保留最高分的测试记录(行)?也就是说,
| student_name | subject | test_number | score |
|--------------|---------|-------------|-------|
| sarah | maths | test1 | 78 |
| sarah | maths | test2 | 71 |
| sarah | maths | test3 | 83 |
| sarah | physics | test1 | 91 |
(2) 我如何保持同一科目、同一学生的所有测试的平均?那就是:
| student_name | subject | test_number | ave_score |
|--------------|---------|-------------|-----------|
| sarah | maths | na | 77.333 |
| sarah | maths | na | 94 |
| sarah | maths | na | 85 |
| sarah | physics | na | 85.5 |
我尝试了df.sort_values() 和df.drop_duplicates(subset=..., keep=...) 的各种组合,但无济于事。
实际数据
| query | target | pct-similarity | p-val | aln_length | bit-score |
|-------|----------|----------------|-------|------------|-----------|
| EV239 | B/Fw6/623 | 99.23 | 0.966 | 832 | 356 |
| EV239 | B/Fw6/623 | 97.34 | 0.982 | 1022 | 739 |
| EV239 | MMS-alpha | 92.23 | 0.997 | 838 | 384 |
| EV239 | MMS-alpha | 93.49 | 0.993 | 1402 | 829 |
| EV380 | B/Fw6/623 | 94.32 | 0.951 | 324 | 423 |
| EV380 | B/Fw6/623 | 95.27 | 0.932 | 1245 | 938 |
| EV380 | MMS-alpha | 99.23 | 0.927 | 723 | 522 |
| EV380 | MMS-alpha | 99.15 | 0.903 | 948 | 1092 |
应用聚合函数后,只有pct-similarity 列会感兴趣。
(1) 通过选择最大的aln_length 删除重复的查询+目标行。保留属于最大aln_length 的行的pct-similarity 值。
(2) 通过选择最大aln_length 的行并计算该组重复行的平均值pct-similarity,聚合重复查询+目标行。其他数字列不是必需的,最终会被删除,所以我真的不在乎对它们应用什么聚合函数(最大值或平均值)。
【问题讨论】: