滚动将条件函数应用于Pandas系列



我有一个简单的标记方法,我想在滚动的基础上应用于Pandas系列。

其想法是在滚动N天的基础上进行观察,并对每个观察结果是否高于、低于或介于阈值之间进行分类。

例如:

阈值=1

如果高于阈值,则为1,如果低于阈值则为0,否则为2。

以下是当前实施情况:

import pandas as pd
# A pandas series of pct returns
pct_returns = pd.Series([0.01, 0.03, 0.07, 0.05, 0.001, 0.01, 0.05, 0.05])
def label(s, threshold):
if s >= threshold: return 1
else: return 0if s <= -threshold else 2
# apply on rolling basis
labels = s.rolling(20).apply(compute_label, args=(0.05,))

遗憾的是,在上面的实现中,我收到了一个TypeError,TypeError: must be real number, not NoneType

期望结果:

我想根据下一个滚动n天来标记pct_return系列——如果pct_return大于/小于阈值,则会对其进行相应分类。

非常感谢您的帮助。

逻辑还不完全清楚,但您需要在数字序列上滚动,然后每行获得一个值,您可以使用它来映射标签。

以下是每个窗口使用max值滚动2天的示例:

s = pct_returns.rolling(2, min_periods=1).max()
threshold = 0.05
labels = np.select([s.gt(threshold), s.le(-threshold)], [1, 0], 2)

输出:array([2, 2, 1, 1, 2, 2, 2, 2])

详细输出为DataFrame:

data  roll_2_max  labels
0  0.010        0.01       2
1  0.030        0.03       2
2  0.070        0.07       1
3  0.050        0.07       1
4  0.001        0.05       2
5  0.010        0.01       2
6  0.050        0.05       2
7  0.050        0.05       2

最新更新