【问题标题】:Filter based on pairs within a group基于组内的对进行过滤
【发布时间】:2021-10-30 06:19:57
【问题描述】:
 Group Code
   1     2
   1     2
   1     4
   1     1
   2     4 
   2     1
   2     2 
   2     3
   2     1
   2     1
   2     3

在每个组中都有对。例如在第 1 组中;对是 (2,2),(2,4),(4,1)

我想根据出现在对开头的代码号 2 过滤这些对。 例如在第 1 组中,只有 (2,2) 和 (2,4) 将被保留,而 (4,1) 将被过滤掉。

异常输出:

 Group Code
   1     2
   1     2
   1     4
   2     2 
   2     3
  

【问题讨论】:

    标签: python pandas dataframe numpy filter


    【解决方案1】:

    检查groupbyshift

    out = df[df.groupby('Group').Code.apply(lambda x : x.eq(2) | x.eq(2).shift())]
    Out[67]: 
       Group  Code
    0      1     2
    1      1     2
    2      1     4
    6      2     2
    7      2     3
    

    【讨论】:

    • 可免申请:df[df.groupby("Group")['Code'].shift().eq(2)|df['Code'].eq(2)]
    • @BENY 我可以将它与多个代码一起使用吗?例如,2 AND 4 是否存在?
    • @tjjudge df[df.groupby('Group').Code.apply(lambda x : x.isin([2,4]) | x.isin([2,4].shift())]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2019-05-06
    • 2013-04-17
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多