【问题标题】:How do you get the last n-th item matching a condition in a pandas series (valuewhen from PineScript)您如何获得匹配熊猫系列中条件的最后第 n 个项目(来自 PineScript 的 valuewhen)
【发布时间】:2020-12-23 18:37:44
【问题描述】:

在 PineScript 中有一个名为 valuewhen 的函数,它在条件为真时返回源的第 n 个最近出现的值。因此,例如,当条件为真时,索引为零将返回最近的值,而索引为 1 将返回第二近的值。

您如何在Series 上使用 Python 中的 Pandas 来做到这一点? PineScript 中的函数签名是valuewhen(condition, source, occurrence) → series[float]

【问题讨论】:

    标签: python pandas time-series pine-script


    【解决方案1】:

    要实现此功能,首先使用重新索引和条件作为掩码删除不需要的值。接下来,根据需要发生的情况来移动系列。然后,使用 reindex 添加从掩码中删除的索引值并首先重新索引。这些索引值将指向np.nan。最后,使用ffill() 将填充值转发到np.nan 值。

    这假设occurrences 是一个有界的非负数,source 是一个有序序列,并且condition 通过它们的index 与源相关。

    这可以用 Python 写成这样:

    def valuewhen(condition, source, occurrence):
        return source \
            .reindex(condition[condition].index) \
            .shift(-occurrence) \
            .reindex(source.index) \
            .ffill()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-07
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2015-04-19
      • 2013-08-19
      • 1970-01-01
      相关资源
      最近更新 更多