[英]Behaviour of nlargest(N) when N greater than number of groups?
我已經從以下列表構建了一個DataFrame
df_list_1 = [{"animal": "dog", "color": "red", "age": 4, "n_legs": 4,},
{"animal": "dog", "color": "blue", "age": 4, "n_legs": 3},
{"animal": "cat", "color": "blue", "age": 4, "n_legs": 4},
{"animal": "dog", "color": "yellow", "age": 5, "n_legs":2},
{"animal": "dog", "color": "white", "age": 4, "n_legs": 2},
{"animal": "dog", "color": "black", "age": 4, "n_legs": 4},
{"animal": "cat", "color": "brown", "age": 4, "n_legs": 4}]
我現在想得到一個新的數據n_legs
每組具有相同n_legs
的前4個條目(按age
排序)。
為此,我試過了
dfg = df_1.set_index(["animal", 'color']).groupby("n_legs")['age'].nlargest(4).reset_index()
但這給了我一個數據幀,其中列n_legs
被刪除。
animal color age
0 dog red 4
1 dog blue 4
2 cat blue 4
3 dog yellow 5
4 dog white 4
5 dog black 4
6 cat brown 4
我想這是因為4等於最大組中的元素數量。 事實上,如果我這樣做
dfg = df_1.set_index(["animal", 'color']).groupby("n_legs")['age'].nlargest(3).reset_index()
我得到以下內容
n_legs animal color age
0 2 dog yellow 5
1 2 dog white 4
2 3 dog blue 4
3 4 dog red 4
4 4 cat blue 4
5 4 dog black 4
這是預期的行為嗎?
是否有一種方法可以始終顯示列,即使使用nlargest(N)
其中N
大於最大組中的元素數量?
謝謝!
在我看來,它是bug 16345 。
替代解決方案工作得很好,顯然更快 - 首先sort_values
然后調用GroupBy.head
:
dfg = (df_1.sort_values(["animal", 'color','age'], ascending=[False, False, True])
.groupby("n_legs")
.head(4))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.