2017-10-07 104 views
1

我有這樣的數據幀:的Python //熊貓 - 選擇的最後一年各指數

  score year ... 
index  
0  123  2015 
0  5354  2016 
0  4314  2014 
12  4542  2018 
12  4523  2017 
13  123  2014 
13  123  2012 
13  231  2016 
... 

我要選擇僅去年每個索引,所以它會看起來像這樣:

  score year ... 
index  
0  123  2016 
12  4542  2018 
13  231  2016 
... 

有人可以照亮它嗎?

回答

3

選項1:

In [188]: df.groupby(level=0, group_keys=False).apply(lambda x: x.nlargest(1, 'year')) 
Out[188]: 
     score year 
index    
0  5354 2016 
12  4542 2018 
13  231 2016 

選項2:

In [193]: df.sort_values('year', ascending=False).groupby(level=0, group_keys=False).head(1) 
Out[193]: 
     score year 
index    
12  4542 2018 
0  5354 2016 
13  231 2016 
+1

希望你喜歡編輯 – Dark

+0

@Bharathshetty,是的,謝謝! :) – MaxU

3

使用drop重複即

ndf = df.reset_index().drop_duplicates('index',keep='first') 

如果今年是無序然後

使用sort_values和降複製

ndf = df.reset_index().sort_values('year').drop_duplicates('index',keep='last') 

ndf =df.reset_index().sort_values('year',ascending=False).drop_duplicates('index',keep='first') 

輸出:

 
    index score year 
1  0 5354 2016 
3  12 4542 2018 
7  13 231 2016 
+0

好點。在上面的例子中,我說他們一直是第一個,但重點是有時他們不是第一個,它可以混合。我會編輯它。 – abutremutante

+0

我得到KeyError:'索引':/你知道這可能是什麼? – abutremutante

+1

嘗試使用'df.reset_index()。sort_values ...'我認爲'index'是一列 – Dark

0

通過使用idxmax

df=df.reset_index() 
df.loc[df.groupby('index').year.idxmax()].set_index('index') 

Out[148]: 
     score year 
index    
0  5354 2016 
12  4542 2018 
13  231 2016