pandas.series.rolling.apply方法似乎将Series隐式转换为numpy数组

时间:2019-02-20 13:11:08

标签: python pandas numpy type-conversion numpy-ndarray

我想计算净值曲线的滚动波动率。

# demo
import pandas as pd

def get_rolling_vol(s: pd.Series) -> float:
    return s.pct_change().iloc[1:].std()

s = pd.Series([1, 1.2, 1.15, 1.19, 1.23, 1.3])
rolling = s.rolling(window=2)
stds = rolling.apply(lambda s: get_rolling_vol(s))

抛出错误:

FutureWarning: Currently, 'apply' passes the values as ndarrays to the applied function. In the future, this will change to passing it as Series objects. You need to specify 'raw=True' to keep the current behaviour, and you can pass 'raw=False' to silence this warning
  stds = rolling.apply(lambda s: get_rolling_vol(s))
... (omits intermediate tracebacks)
AttributeError: 'numpy.ndarray' object has no attribute 'pct_change'

是否有任何方法可以使参数作为Series而不是ndarrays中的apply传递? FutureWarning说将来会这样,如果我现在想要的话该怎么办? (不想修改get_rolling_vol函数,因为还有许多其他函数也假定参数为Series,而修改所有这些函数将很繁琐。)谢谢。

1 个答案:

答案 0 :(得分:1)

是的,这是可能的,如警告消息中所述:在raw=False中使用rolling.apply作为参数

这至少在熊猫0.24.1中有效