简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM