简体   繁体   中英

Pandas time series - need to extract row value based on multiple conditionals based on other columns

I have a time series dataframe with the below columns. I am trying to figure out:

If df['PH'] ==1, then I need find the previous date where df['pivot_low_1'] == 1 and extract the value of df['low'] for that date. So, for 2010-01-12 where df['PH'] ==1, I would need to identify the previous non-zero df['pivot_low_1'] == 1 on 2010-01-07 and get df['low'] == 1127.00000.

                  low  pivot_low_1  PH
date                                  
2010-01-04 1114.00000            1   0
2010-01-05 1125.00000            0   0
2010-01-06 1127.25000            0   0
2010-01-07 1127.00000            1   0
2010-01-08 1131.00000            0   0
2010-01-11 1137.75000            0   0
2010-01-12 1127.75000            1   1
2010-01-13 1129.25000            0   0
2010-01-14 1138.25000            0   0
2010-01-15 1127.50000            1   0
2010-01-18 1129.50000            0   0
2010-01-19 1126.25000            0   0
2010-01-20 1125.25000            0   0
2010-01-21 1108.50000            0   0
2010-01-22 1086.25000            1   0
2010-01-25 1089.75000            0   0
2010-01-26 1081.00000            0   0
2010-01-27 1078.50000            0   0
2010-01-28 1074.25000            0   0
2010-01-29 1066.50000            1   1
2010-02-01 1068.00000            0   0

since you want a column in same dataframe but the output is correspondent to only certain rows, I will be replacing every other column with nan values,

data = pd.read_csv('file.csv')
data.columns=['low', 'pivot_low_1', 'PH']
count = 0
l = list()
new=list()
for index, row in data.iterrows():
    if row['pivot_low_1']==1:
        l.append(count)
    if (row['PH']==1) and (row['pivot_low_1']==1):
        new.append(data.iloc[l[len(l)-2]].low)
    elif (row['PH']==1):
        new.append(data.iloc[l[len(l)-1]].low)
    elif (row['PH']==0):
        new.append(np.nan)
    count+=1
data['new'] = new
data

The output is as shown in this image, https://imgur.com/a/IqowZHZ , hope this helps

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