Reputation: 515
I want to select the top N rows of dataframe sorted by the column price in descending order. But if I have other rows in the dataframe that has a price equal to the last row (N-th row), I want to show them as well. How to proceed?
Suppose I have these 3 rows: id price
A 30
B 35
C 30
D 15
Suppose N = 2:
car_dataframe.sort_values(by=['price'], ascending=False, inplace=True)
return car_dataframe[:2]
This would return:
B 35
A 30
But because C has the same price of the last N-th row(A), I want to return C as well. So it should return:
B 35
A 30
C 30
Upvotes: 2
Views: 166
Reputation: 42916
Use DataFrame.nlargest
with keep="all"
:
df.nlargest(n=2, columns="price", keep="all")
id price
1 B 35
0 A 30
2 C 30
Upvotes: 5