我有一个如下所示的数据框:
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
谢谢!
% timeit temp=dfd.groupby('bucket', as_index=False).apply(lambda x: x.iloc[:-1])
1个循环,3个中最好的结果:每个循环17.1秒 - clg4temp=dfd.groupby('bucket', as_index=False).cumcount(ascending=False)
1 次循环,3 次中的最佳表现:每次循环耗时 4.24 秒 - clg4