Home > Back-end >  Get all rows after a column value occurs pandas
Get all rows after a column value occurs pandas

Time:10-25

Suppose I have this dataframe:

Col1  Col2

128   False
129   True
130   True
183   False
184   True
202   False
203   True
204   True

and I would like to have lists (or a list of tuples) like:

(128, 129, 130) , (183, 184) , (202, 203, 204)

So, my question is: How can I slice a dataframe by a column value and get all rows after (including) that column value?

The column value in this case is 'False'. Thank you in advance!!

CodePudding user response:

You can create groups by each False values and aggregate tuples:

L = df.groupby((~df['Col2']).cumsum())['Col1'].agg(tuple).tolist()
print (L)
[(128, 129, 130), (183, 184), (202, 203, 204)]

Or if need consecutive values by Col1 use:

L = df.groupby(df['Col1'].diff().ne(1).cumsum())['Col1'].agg(tuple).tolist()
print (L)
[(128, 129, 130), (183, 184), (202, 203, 204)]
  • Related