简体   繁体   中英

Applying custom function with rolling window row-wise in pandas

I have a function that I want to apply to row-wise down the dataframe and output a new new column with the result. Normally this would be straightforward with a lambda function or .map() but I am stuck because the function requires a rolling min / max with a window and lambda will obviously only see that row.

Here is the function:

def divergence(series_1, series_2, local_window = 5, reference_window = 15):
    min_1_local = series_1.rolling(local_window).min().iloc[-1]
    min_1_reference = series_1.rolling(reference_window).min().iloc[-1]

    min_2_local = series_1.rolling(local_window).min().iloc[-1]
    min_2_reference = series_1.rolling(reference_window).min().iloc[-1]

    max_1_local = series_1.rolling(local_window).max().iloc[-1]
    max_1_reference = series_1.rolling(reference_window).max().iloc[-1]

    max_2_local = series_1.rolling(local_window).max().iloc[-1]
    max_2_reference = series_1.rolling(reference_window).max().iloc[-1]

    if ( (min_1_local < min_1_reference) 
        & (min_2_local > min_2_reference) 
        & (series_2.iloc[-1] > series_2.iloc[-2]) ):
        return 1
    elif ( (max_1_local > max_1_reference) 
          & (max_2_local < max_2_reference) 
          & (series_2.iloc[-1] < series_2.iloc[-2]) ):
        return -1
    else:
        return 0

and here is what my data looks like:

    Measure1    Measure2
Date        
2018-09-18 05:00:00 1912.345679 -28.291456
2018-09-18 06:00:00 1910.802469 -28.351495
2018-09-18 07:00:00 1916.666667 -27.988846
2018-09-18 08:00:00 1907.253086 -28.039686
2018-09-18 09:00:00 1907.098765 -28.091198

Any ideas?

Have you tried pandas rolling function ?

df = pd.DataFrame(np.random.rand(50,2), columns=['input1', 'input2'])
df['min'] = df['input1'].rolling(5).min()
df['min_shifted'] = df['input1'].rolling(5).min().shift(-5)

在此处输入图片说明

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