【问题标题】:Groupby with boolean condition True in one of the columns in Pandas在 Pandas 的一列中具有布尔条件 True 的 Groupby
【发布时间】:2018-06-08 08:07:48
【问题描述】:

这是我想使用 groupby 的数据框

Value           Boolean1        Boolean2
 5.175603       False           False
 5.415855       False           False
 5.046997       False           False
 4.607749       True            False
 5.140482       False           False
 1.796552       False           False
 0.139924       False           True
 4.157981       False           True
 4.893860       False           False
 5.091573       False           False
 6              True            False
 6.05           False           False

我想将groupbyBoolean1 and Boolean2 列一起使用。 groupbyFalse 继续到,除非它找到 True 并且它检查两个列,然后再次将下一个 False 变为 True。如果不再存在 True,那么它可以忽略其余的 False(与其对应的值),或者它可以存在

我想实现类似的。

Value       Boolean1            Boolean2

这是一组

 5.175603       False               False
 5.415855       False               False
 5.046997       False               False
 4.607749       True                False

这是另一个

5.140482        False               False
 1.796552       False               False
 0.139924       False               True 
4.157981        False               True

这是另一个

 4.893860       False               False
 5.091573       False               False
 6              True                False

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我的想法是在至少一个True 列之前检查两列中的Falses:

    #chain condition together by OR and invert
    m = ~(df['Boolean1'] | df['Boolean2'])
    #get consecutive groups with AND for filter only Trues 
    #(because inverting, it return False in both cols)
    s = (m.ne(m.shift()) & m).cumsum()
    
    for i, x in df.groupby(s):
        print (x)
    
    dtype: int32
          Value  Boolean1  Boolean2
    0  5.175603     False     False
    1  5.415855     False     False
    2  5.046997     False     False
    3  4.607749      True     False
          Value  Boolean1  Boolean2
    4  5.140482     False     False
    5  1.796552     False     False
    6  0.139924     False      True
    7  4.157981     False      True
           Value  Boolean1  Boolean2
    8   4.893860     False     False
    9   5.091573     False     False
    10  6.000000      True     False
        Value  Boolean1  Boolean2
    11   6.05     False     False
    

    详情

    print (m)
    0      True
    1      True
    2      True
    3     False
    4      True
    5      True
    6     False
    7     False
    8      True
    9      True
    10    False
    11     True
    dtype: bool
    
    print (s)
    0     1
    1     1
    2     1
    3     1
    4     2
    5     2
    6     2
    7     2
    8     3
    9     3
    10    3
    11    4
    dtype: int32
    

    【讨论】:

      猜你喜欢
      • 2020-04-01
      • 1970-01-01
      • 2022-01-23
      • 2021-04-06
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多