【问题标题】:Using Pandas, how do I drop the last row of each group?使用 Pandas,如何删除每组的最后一行?
【发布时间】:2014-03-26 19:13:56
【问题描述】:

我有一个如下图所示的数据框:

import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three', 'three', 'one'], 'B': range(6)})
grouped = df.groupby('A')
print grouped.head()

             A  B
A                
one   0    one  0
      1    one  1
      5    one  5
three 3  three  3
      4  three  4
two   2    two  2

我可以通过以下方式轻松选择每组的最后一行:

print(grouped.agg(lambda x: x.iloc[-1]))

      B
A       
one    5
three  4
two    2

如何改为删除每个组的最后一行?结果是:

       A  B
0    one  0
1    one  1
3  three  3

我尝试过过滤,但它似乎没有做任何事情:

print grouped.filter(lambda x: x.iloc[-1])

       A  B
0    one  0
1    one  1
5    one  5
3  three  3
4  three  4
2    two  2

谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    怎么样:

    >>> df.groupby("A", as_index=False).apply(lambda x: x.iloc[:-1])
           A  B
    0    one  0
    1    one  1
    3  three  3
    
    [3 rows x 2 columns]
    

    【讨论】:

    • 在 pandas 0.12.0 中,对我来说,索引仍然显示为“A”(带有该标签)。
    【解决方案2】:

    您可能会发现使用cumcount 会更快:

    In [11]: df[grouped.cumcount(ascending=False) > 0]
    Out[11]: 
           A  B
    0    one  0
    1    one  1
    3  three  3
    

    【讨论】:

    • 不错。并且应该至少快几倍。
    • @DSM 我确实想知道这是否应该作为 head(-2) 或 tail(-2) 提供......可能不是。
    • 40m 记录的时间 df:% timeit temp=dfd.groupby('bucket', as_index=False).apply(lambda x: x.iloc[:-1]) 1 次循环,最好的 3 次:每次循环 17.1 秒
    • % timeit temp=dfd.groupby('bucket', as_index=False).cumcount(ascending=False) 1 个循环,最好的 3 个:每个循环 4.24 秒
    猜你喜欢
    • 2020-10-07
    • 2018-04-27
    • 1970-01-01
    • 2019-09-20
    • 2020-06-28
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2016-12-12
    相关资源
    最近更新 更多