簡體   English   中英

使用 Pandas,如何刪除每組的最后一行?

[英]Using Pandas, how do I drop the last row of each group?

我有一個 dataframe 如下圖所示:

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

我可以通過執行以下操作輕松 select 每組的最后一行:

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

謝謝

怎么樣:

>>> 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]

您可能會發現使用cumcount更快:

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

這樣做:

df.drop(df.groupby('A').tail(1).index, axis=0)

您可以使用duplicated的方法:

df[df.duplicated('A', keep='last')]

Output:

       A  B
0    one  0
1    one  1
3  three  3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM