如何对 pandas 数据框中的 n+ 个条目进行切片?

jim*_*mmy 2 python dataframe pandas

我想选择按列价格降序排列的数据帧的前 N ​​行。但是,如果数据框中有其他行的价格等于最后一行(第 N 行),我也想显示它们。如何进行?

假设我有这 3 行: id 价格

A  30
B  35 
C  30
D  15
Run Code Online (Sandbox Code Playgroud)

假设 N = 2:

car_dataframe.sort_values(by=['price'], ascending=False, inplace=True)
return car_dataframe[:2]
Run Code Online (Sandbox Code Playgroud)

这将返回:

B 35
A 30
Run Code Online (Sandbox Code Playgroud)

但因为 C 与最后 N 行(A)的价格相同,所以我也想返回 C。所以它应该返回:

B 35
A 30
C 30
Run Code Online (Sandbox Code Playgroud)

Erf*_*fan 5

DataFrame.nlargest与以下一起使用keep="all"

df.nlargest(n=2, columns="price", keep="all")
Run Code Online (Sandbox Code Playgroud)
  id  price
1  B     35
0  A     30
2  C     30
Run Code Online (Sandbox Code Playgroud)