【问题标题】:Selecting the last year for each index in Pandas为 Pandas 中的每个索引选择最后一年
【发布时间】:2017-10-07 14:26:44
【问题描述】:

我有这个数据框:

         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


    【解决方案1】:

    选项 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
    

    【讨论】:

      【解决方案2】:

      使用删除重复,即

      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')
      

      输出:

      指数分数年 1 0 5354 2016 3 12 4542 2018 7 13 231 2016

      【讨论】:

      • 好点。在上面的例子中,我说他们总是第一个,但关键是有时他们不是第一个,它可以混合使用。我会编辑它。
      • 我收到 KeyError: 'index' :/ 你知道那可能是什么吗?
      • 尝试使用df.reset_index().sort_values... 我认为index 是一列
      【解决方案3】:

      通过使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-27
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-07
        • 2016-07-14
        • 2020-07-18
        相关资源
        最近更新 更多