【问题标题】:Filter rows from ogrouped data frames based on string & boolean columns根据字符串和布尔列从 ogrouped 数据帧中过滤行
【发布时间】:2022-08-17 17:15:10
【问题描述】:

我有以下数据框:

data = {
      \'Day\':[7,7,7,7,5,5,5,5],
     \'Direction\': [\"North\",\"NorthEast\",\"NorthWest\",\"West\",\"East\",\"EastWest\",\"EastNorth\",\"West\"],
    \'Bool\':[True,False,False,False,True,False,False,False],}

df = pd.DataFrame(data)
df.groupby([\"Day\"])

      Day  Direction   Bool
  0    7      North   True  
  1    7  NorthEast  False
  2    7  NorthWest  False
  3    7       West  False
  4    5       East   True
  5    5   EastWest  False
  6    5  EastNorth  False
  7    5       West  False

我想按天过滤每个组,字符串列df[\'Direction\'] 不包含在df[\'Direction\'] 的行中的行,其中df[\'Bool\']True

因此,例如在第一组中,df[\'Direction\']= \"West\" 它与df[\"direction\"]= \"North\" 不匹配(其中df[\"Bool\"]== True)所以它被丢弃了。 df[\"Direction\"]=\"NorthWest\" 是一个匹配项,因为字符串包含 North 所以它被保留了。

预期输出:

      Day  Direction   Bool
  0    7      North   True  
  1    7  NorthEast  False
  2    7  NorthWest  False
  3    5       East   True
  4    5   EastWest  False
  5    5  EastNorth  False

这些行并不总是具有相同的顺序,因此不能使用shift()。我想知道是否有一种快速的方法可以在不使用循环的情况下做到这一点。

    标签: python pandas dataframe


    【解决方案1】:

    IIUC,您可以将groupby.apply 与布尔切片一起使用:

    (df.groupby('Day', sort=False, group_keys=False)
       .apply(lambda g: g[g['Direction'].str.contains('|'.join(g.loc[g['Bool'], 'Direction']))])
    )
    

    输出:

       Day  Direction   Bool
    0    7      North   True
    1    7  NorthEast  False
    2    7  NorthWest  False
    4    5       East   True
    5    5   EastWest  False
    6    5  EastNorth  False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-15
      • 2012-12-06
      • 2013-09-11
      • 2015-05-08
      • 2021-06-20
      • 2011-02-05
      • 2021-03-21
      • 2019-12-27
      相关资源
      最近更新 更多