who*_*ver 5 python group-by pandas
我在过滤pandas.DataFrame的每组groupby对象中除了最后1个元素之外的所有元素时遇到了问题:
x = pd.DataFrame([['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]],
columns=['A', 'B'])
g = x.groupby('A')
Run Code Online (Sandbox Code Playgroud)
正如预期(根据文件)g.head(1)返回
A B
0 a 1
1 b 1
Run Code Online (Sandbox Code Playgroud)
而g.head(-1)返回空DataFrame
从x.head(-1)我期望它的行为返回
A B
0 a 1
1 b 1
2 a 2
3 b 2
Run Code Online (Sandbox Code Playgroud)
即删除每个组的最后一个元素,然后将其合并回数据帧.如果这只是熊猫中的错误,我会感激任何提出替代方法的人.
正如所评论的,这些还没有在 pandas 中实现。但是,您可以使用 cumcount 来有效地实现它们:
def negative_head(g, n):
return g._selected_obj[g.cumcount(ascending=False) >= n]
def negative_tail(g, n):
return g._selected_obj[g.cumcount() >= n]
In [11]: negative_head(g, 1) # instead of g.head(-1)
Out[11]:
B
0 1
1 1
2 2
3 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
789 次 |
| 最近记录: |