how to get max count of consecutive 1 in column pandas

Viewed 157

I Have one dataframe with column Flag1 in this, I want to check if in column flag value 1 occurs continuously for maximum times

Here is the dataframe and output format

df = pd.DataFrame({'flag':[1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1]}) 
df_out = pd.DataFrame({'max_count':[3]})
3 Answers

Solution with pandas

m = df['flag'].eq(1)
max(m[m].groupby((~m).cumsum()).sum())

Solution with itertools.groupby

from itertools import groupby

max(sum(g) for k, g in groupby(df['flag']) if k == 1)

Result

3

I provided an answer to a similar problem here:

You can do:

s = df['flag']

(s.groupby(((s-s.shift().fillna(0)).eq(1).cumsum()*s))
  .transform(len)*s
).max()

output: 3

Related