【问题标题】:pandas.series.rolling.apply method seems to implicitly convert Series into numpy arraypandas.series.rolling.apply 方法似乎将 Series 隐式转换为 numpy 数组
【发布时间】:2019-07-14 04:35:44
【问题描述】:

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

# 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 而不是apply 中的ndarraysFutureWarning 表示以后会这样,如果我现在想要呢? (不想修改 get_rolling_vol 函数,因为还有许多其他函数也假定参数是 Series 并且修改所有这些函数会很乏味。)谢谢。

【问题讨论】:

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


    【解决方案1】:

    是的,这是可能的,如警告消息中所述:Use raw=False as argument in rolling.apply

    这至少在 pandas 0.24.1 中有效

    【讨论】:

    • 不,这在我的机器上不起作用。设置 raw=True 只会使警告静音,但实际上参数仍然作为 ndarray 传递。
    • 使用raw=False 将其作为一个系列获取并消除警告。
    • 正如另一条评论所暗示的,它应该是raw=False
    猜你喜欢
    • 2020-11-09
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多