简体   繁体   中英

Populate Pandas Dataframe column from other columns based on a condition and previous row value

I have following Pinescript statements that I'm trying to implement using python dataframes.

Hlv = float(na)
Hlv := close > sma_high ? 1 : close < sma_low ? -1 : Hlv[1]

Line 1 - Hlv - is basically a variable name which is a float

Line 2 - Assinging new value to variable, ternary operator (if-elseif-else). The assignment Hlv[1] means previous value (value of Hlv , 1 step(row) back)

Now Implementing this in Dataframe having following columns and data ->

Current ->

Close SMA_High SMA_Low 
 10      12      5
 12      14      6
 13      17      7

Now, I want to add another column called HLV storing Hlv values for each row, based on the condition we will compute as in pinescript line2.

Expected ->

Close SMA_High SMA_Low  Hlv
 10      9       5       1     // close > sma_high = 1
 5       14      6       -1    // close < sma_low = -1
 13      17      7       -1    // here no conditions are met , so previous value of Hlv is taken i.e -1

I am not able to figure out how to generate this new column with values deriving from other columns and even how to take previous value of the column.

I went through this answer and could see we could add values on condition as below -

df['Hlv'] = pd.NA
df.loc[df.Close>df.SMA_High,'Hlv'] = 1
df.loc[df.Close<df.SMA_Low,'Hlv'] = -1

But still not sure how can I populate with previous value if no conditions are met / default case . Thanks in advance.

import numpy as np
df['Hlv'] = np.NaN
df.loc[df.Close>df.SMA_High,'Hlv'] = 1
df.loc[df.Close<df.SMA_Low,'Hlv'] = -1
df.fillna(method='ffill',inplace=True)

Easier to just set your default value beforehand, eg:

df['Hlv'] = 0  # This is your default value
df.loc[df.Close > df.SMA_High, 'Hlv'] = 1
df.loc[df.Close < df.SMA_Low, 'Hlv'] = -1

If you still want to ffill with the previous row, then refer to your default value:

df.Hlv.replace(0, method='ffill')  # 0 being your default value

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