讓我們說有一個資料框df
Name Balance
A 1000
B 5000
C 3000
D 6000
E 2000
F 5000
我正在尋找一種方法,通過它我可以獲得三行中余額最高的行。
df['balance'].get_indices_max(n=3) # where is no. of results required
當這些索引將用于獲取行時輸出:
D 6000
F 5000
B 5000
更新:關于接受的答案的額外說明
可能的“保留”值 -
first : prioritize the first occurrence(s)
last : prioritize the last occurrence(s)
all : do not drop any duplicates, even it means selecting more than n items.
uj5u.com熱心網友回復:
回答
df = Df({"Name":list("ABCDEF"), "Balance":[1000,5000,3000,6000,2000,5000]})
index = df["Balance"].nlargest(3).index
df.loc[index]
輸出
Name Balance
3 D 6000
1 B 5000
5 F 5000
關注
- 高性能
未指定的列也會回傳,但不用于排序。此方法等效于 df.sort_values(columns, ascending=False).head(n),但性能更高。
nlargest(3, keep='all')
保持{'first', 'last', 'all'},默認'first'
使用keep='all'時,保留所有重復項
例子
df = Df({"Name":list("ABCDEFX"), "Balance":[1000,5000,3000,6000,2000,5000,5000]})
index = df["Balance"].nlargest(3, keep='all').index
df.loc[index]
Name Balance
3 D 6000
1 B 5000
5 F 5000
6 X 5000
參考
- DataFrame.nlargest
uj5u.com熱心網友回復:
我通常做
out = df.sort_values('Balance').iloc[3:]
Out[476]:
Name Balance
1 B 5000
5 F 5000
3 D 6000
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474474.html
上一篇:OR上的Mysql查詢例外緩慢
