dmd7
dmd7

Reputation: 641

Count or flag number of times dataframe column reaches a condition

What I'm looking to do to is add a new column that essentially 'flags' if a condition is met in a separate column - where if the next value < previous value then flag it. For simplicity lets go with 1 (yes) and 0 (no). Example below:

DF_original:

Col1 
  4
  5
  3
  9
  12
  11
  15

DF_desired:

Col1      Col_flag
  4           0
  5           0
  3           1
  9           0
  12          0
  11          1
  15          0

Thanks for the help.

Upvotes: 1

Views: 110

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18377

You can do it with np.where() and diff():

df = pd.DataFrame({'col1':[4,5,3,9,12,11,15]})
df['Col2'] = np.where(df['col1'].diff() < 0,1,0)

This would output:

   col1  Col2
0     4     0
1     5     0
2     3     1
3     9     0
4    12     0
5    11     1
6    15     0

Upvotes: 1

Related Questions