![](/img/trans.png)
[英]Select top 5 from each month using value counts on a DateTimeIndex with Pandas
[英]Python pandas select top 2 from each column
我有一個巨大的 dataframe 為:
Na Col1 Col2 Col3 Col4
A 77 42 88
B 31 64
C 86 79 79 99
D 94 8 95
E 95 40 27
F 92 71 32
我想從每列的前 2 個 select 創建以下內容:
Na Col1 Col2 Col3 Col4
A 88
C 79 79 99
D 94 95
E 95
F 92
除了循環遍歷 dataframe 的每一列並從外部加入它們之外,我不知道如何解決這個問題,但我原來的 dataframe 非常大。
看起來您可以在每一列中使用nlargest
,設置n=2
來檢索前 2 個項目。
df.set_index('Na').apply(pd.Series.nlargest, n=2)
Col1 Col2 Col3 Col4
A NaN NaN 88.0 NaN
C NaN 79.0 NaN 99.0
D NaN 94.0 88.0 95.0
E 95.0 NaN NaN NaN
F 92.0 NaN NaN NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.