python - 具有 bool 条件的 Groupby 在 Pandas 的其中一列中为真

标签 python pandas dataframe

这是我要使用 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 和 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

最佳答案

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

#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

关于python - 具有 bool 条件的 Groupby 在 Pandas 的其中一列中为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50756169/

相关文章:

python - 基于针对另一列的引用表更新 Pandas Dataframe 列的问题

python - 映射字典与大陆 : Country to a DataFrame with a Country Column

python - 将新列计算为 Pandas 中其他列的平均值

python - 将数组中的每个值复制为一个新数组

python - 创建 for 循环以使用 Seaborn 为 DataFrame 的各个列绘制直方图

python - 计算结构中的截留水

python - PyCharm - 使用 pandas 或 numpy 时调试卡住

python - 如何重命名具有相同列名的数据框的列?

python - 生成总和等于 0 的 N 个随机单位向量(Python)

python - 访问在远程服务器上运行的 Ipython Notebook