我有一个数据帧,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方式轻松选择每个组的最后几行:
print(grouped.agg(lambda x: x.iloc[-1]))
B
A
one 5
three 4
two 2
Run Code Online (Sandbox Code Playgroud)
如何删除每个组的最后一行?结果将是:
A B
0 one 0
1 one 1
3 three 3
Run Code Online (Sandbox Code Playgroud)
我尝试过滤但似乎没有做任何事情:
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
Run Code Online (Sandbox Code Playgroud)
谢谢
DSM*_*DSM 10
怎么样:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
您可能会发现使用cumcount更快:
In [11]: df[grouped.cumcount(ascending=False) > 0]
Out[11]:
A B
0 one 0
1 one 1
3 three 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3842 次 |
| 最近记录: |