选择Pandas中每个索引的最后一年

问题描述 投票:1回答:3

我有这个数据帧:

         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
...
python pandas grouping
3个回答
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

3
投票

使用drop duplicates即

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
投票

通过使用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
© www.soinside.com 2019 - 2024. All rights reserved.