gpt4 book ai didi

python - 使用 Pandas,如何删除每组的最后一行?

转载 作者:太空狗 更新时间:2023-10-29 18:24:25 24 4
gpt4 key购买 nike

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

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

谢谢!

最佳答案

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

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

关于python - 使用 Pandas,如何删除每组的最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com