2017-10-07 66 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