简体   繁体   中英

Python - Equal Previous Value in Adjacent Column

The desired outcome is to generate a value in column 'Low' next to every '1' value in column 'Signal'.

The value of 'Low' should be the previous value of 'Low Indi' based on the date of the Signal value.

As you can see the first 'Low' value below is 33. There is a value here because 'Signal' equals '1', and the previous value (vs 16/04/2020) of 'Low Indi' is 33.

import pandas as pd 
import matplotlib.pyplot as plt
import mplfinance as mpf
import numpy as np
import matplotlib.dates as mdates 
from scipy import signal
from scipy.signal import argrelextrema


data = pd.read_excel('PrevLowExample.xlsx', index_col=0, parse_dates=True)

print(data)

This is the desired output.

            Data  Low Indi  Signal   Low
Date                                    
2020-04-17    96       NaN     NaN   NaN
2020-04-16    42       NaN     1.0  33.0
2020-04-15    33      33.0     NaN   NaN
2020-04-14    25       NaN     NaN   NaN
2020-04-13    85       NaN     1.0  55.0
2020-04-12    77       NaN     NaN   NaN
2020-04-11    29       NaN     NaN   NaN
2020-04-10    55      55.0     NaN   NaN
2020-04-09    85       NaN     NaN   NaN
2020-04-08    57       NaN     1.0  71.0
2020-04-07    60       NaN     NaN   NaN
2020-04-06    71      71.0     NaN   NaN
2020-04-05    50       NaN     NaN   NaN

The easiest way is to backfill NaN values and then do a filter

data['Low'] = data['Low Indi'].fillna(method='bfill')
data.loc[data.Signal.isnull(), 'Low'] = np.nan

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