Pandas: how to groupby based on series pattern
问题 Having the following df: pd.DataFrame({'bool':[True,True,True, False,True,True,True], 'foo':[1,3,2,6,2,4,7]}) which results into: bool foo 0 True 1 1 True 3 2 True 2 3 False 6 4 True 2 5 True 4 6 True 7 how to groupby Trues into 2 groups, to have indexes [0:2] in group 1 , and [4:6] in group 2 ? The desired output: group1: bool foo 0 True 1 1 True 3 2 True 2 group2: 4 True 2 5 True 4 6 True 7 Thank you! 回答1: you could do : import numpy as np x = df[df["bool"]].index.values groups = np.split(x