-1

I have a column with numbers. I want to count the maximum number of consecutive negative numbers (ie: negative numbers in a row) in the column like below.

I think I should mask negative numbers first, but I could not figure it out.

  numbers  max_cons
0       -1         1
1        3         1
2        2         1
3       -3         1
4       -4         2
5        9         2
6        3         2

Any help would be appreciated.

Thanks

Emi OB
  • 2,814
  • 3
  • 13
  • 29
tompal18
  • 1,164
  • 2
  • 21
  • 39

1 Answers1

1

Use:

m = df['numbers'].lt(0)
s = (m.shift(-1) & m).cumsum()[m]

df['max_cons'] = s.map(s.value_counts()).mask(~s.duplicated())

df['max_cons'] = df['max_cons'].ffill().fillna(1).astype(int)
print (df)
   numbers  max_cons
0       -1         1
1        3         1
2        2         1
3       -3         1
4       -4         2
5        9         2
6        3         2
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252