如何在Pandas中删除每组的最后一行?
我有一个数据框,内容如下:
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
谢谢!
4 个回答
0
1
这样做:
df.drop(df.groupby('A').tail(1).index, axis=0)
12
这样怎么样:
>>> 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]
15
你可能会发现使用 cumcount 这个方法更快:
In [11]: df[grouped.cumcount(ascending=False) > 0]
Out[11]:
A B
0 one 0
1 one 1
3 three 3