【问题标题】:Taking different records from groups using group by in pandas在 pandas 中使用 group by 从组中获取不同的记录
【发布时间】:2020-10-08 08:59:15
【问题描述】:

假设我有这样的数据框

>>> df = pd.DataFrame({'id':[1,1,1,2,2,2,2,3,4],'value':[1,2,3,1,2,3,4,1,1]})
>>> df
   id  value
0   1      1
1   1      2
2   1      3
3   2      1
4   2      2
5   2      3
6   2      4
7   3      1
8   4      1

现在我想使用组 ID 将每个组中的所有记录排在最前面,除了最后 3 条记录。这意味着我想删除所有组中的最后 3 条记录。我如何使用 pandas group_by 来做到这一点。这是虚拟数据。

【问题讨论】:

  • 请发布预期输出

标签: python-3.x pandas group-by


【解决方案1】:

GroupBy.cumcount 用于ascending=False 后面的计数器,然后通过Series.gt 进行比较以获得更大的值,例如2,因为python 计数来自0

df = df[df.groupby('id').cumcount(ascending=False).gt(2)]
print (df)
   id  value
3   2      1

详情

print (df.groupby('id').cumcount(ascending=False))
0    2
1    1
2    0
3    3
4    2
5    1
6    0
7    0
8    0
dtype: int64

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2021-01-20
    • 2020-12-19
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    相关资源
    最近更新 更多