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?
答案 0 :(得分:0)
您尝试过大熊猫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)