shape: (5, 2)
Student | Score |
---|---|
str | i64 |
"Harvey" | 88 |
"Donna" | 76 |
"Mike" | 93 |
"Jessica" | 85 |
"Louis" | 91 |
top_k
Joram Mutenge
2025-08-15
Sorting values is an expensive operation, especially when you have a large dataset. However, sometimes you have no choice but to sort the data, particularly when you need to pick the top 5 or 10 values. Below is a dataframe showing student scores on a test.
Student | Score |
---|---|
str | i64 |
"Harvey" | 88 |
"Donna" | 76 |
"Mike" | 93 |
"Jessica" | 85 |
"Louis" | 91 |
Suppose you want to get the three students with the highest scores without sorting the data first. How can you do it? Polars has the method top_k
, which you can use to accomplish exactly that.
If you want to get the bottom 3 students, use bottom_k
.
Sign up for my Polars course to improve your data analysis skills.