I have created the following pandas dataframe:
import pandas as pd
import numpy as np
ds = {'col1' : [234,321,284,286,287,300,301,303,305,299,288,300,299,287,286,280,279,270,269,301]}
df = pd.DataFrame(data=ds)
The dataframe looks like this:
display(df)
col1
0 234
1 321
2 284
3 286
4 287
5 300
6 301
7 303
8 305
9 299
10 288
11 300
12 299
13 287
14 286
15 280
16 279
17 270
18 269
19 301
I have then created two columns (cnsIncr , cnsDecr), which calculate the consecutive increase and decrease in col1 respectively.
cnsIncr = []
cnsDecr = []
col1 = np.array(df['col1'])
for i in range(len(df)):
cnsIncr.append(0)
cnsDecr.append(0)
if(col1[i] > col1[i-1]):
cnsIncr[i] = cnsIncr[i-1]+1
else:
cnsIncr[i] = 0
if(col1[i] < col1[i-1]):
cnsDecr[i] = cnsDecr[i-1]+1
else:
cnsDecr[i] = 0
df['cnsIncr'] = cnsIncr
df['cnsDecr'] = cnsDecr
The resulting dataframe looks as follows:
I need to create a columns called Trend which is populated as follows:
- if the column
cnsIncrcontains a value greater or equal to 5, thenTrend = UpTrendstarting from the record in whichconsIncr = 0and ending at the record for whichcnsIncr >= 5; - if the column
cnsDecrcontains a value greater or equal to 5, thenTrend = DownTrendstarting from the record in whichcnsDecr = 0and ending at the record for whichcnsDecr >= 5; - the neither the column
cnsIncrnor the columncnsDecrcontain a value of 5, thenTrend = NoTrend
So, from the example above, the resulting dataframe would look like this:
How can I do this?

