【问题标题】:Filter based on pairs within a group - if value represent at BOTH ends基于组内的对进行过滤 - 如果值代表两端
【发布时间】:2021-09-01 22:12:20
【问题描述】:
 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 和 4 过滤这些对(不是任何一个)

例如,在第 1 组中,只有 (2,4) 将被保留,而 (2,2) 和 (4,1) 将被过滤掉。 异常输出:

 Group Code
  1     2
  1     4
 

【问题讨论】:

  • 如果您要求 2 和 4 都存在,则表示 2 个不同的值。现在了解

标签: python pandas dataframe numpy filter


【解决方案1】:

可以通过在2或4中为当前行和下一行代码制作2个布尔掩码来接近,然后形成present at BOTH ends(not either)所需的组合条件,如下:

如果您要求这对中同时存在 2 和 4,那么我们可以创建另一个布尔掩码来断言这两个连续的代码不相等:

m_curr = df['Code'].isin([2,4])                                # current row code is 2 or 4
m_next = df.groupby("Group")['Code'].shift(-1).isin([2,4])     # next row code in same group is 2 or 4
m_diff = df['Code'].ne(df.groupby("Group")['Code'].shift(-1))  # different row codes in current and next row in the same group

# current row AND next row code in 2 or 4 AND (2 and 4 both present, i.e. the 2 values in pair are diffrent)
mask = m_curr & m_next & m_diff

df[mask | mask.shift()]

结果:

   Group  Code
1      1     2
2      1     4

另一种方法,对于这种特殊情况可能会更简单一些:

m1 = df['Code'].eq(2) & df.groupby("Group")['Code'].shift(-1).eq(4)   # current row is 2 and next row in same group is 4
m2 = df['Code'].eq(4) & df.groupby("Group")['Code'].shift(-1).eq(2)   # current row is 4 and next row in same group is 2

mask = m1 | m2     # either pair of (2, 4) or (4, 2)

df[mask | mask.shift()]

结果:

同样的结果:

   Group  Code
1      1     2
2      1     4

【讨论】:

    【解决方案2】:

    你可以试试shift

    s = df.groupby('Group')['Code'].apply(lambda x : (x==4) & (x.shift()==2))
    out = df[s | s.shift(-1)]
    Out[97]: 
       Group  Code
    1      1     2
    2      1     4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-30
      • 2021-02-28
      • 2019-08-27
      • 2016-11-03
      • 2020-12-11
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多