-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,000
  • 2
  • 10
  • 22
tompal18
  • 984
  • 1
  • 16
  • 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
  • 729,927
  • 78
  • 1,141
  • 1,090