简体   繁体   English

您如何获得与 pandas 系列中的条件匹配的最后第 n 个项目(来自 PineScript 的 valuewhen)

[英]How do you get the last n-th item matching a condition in a pandas series (valuewhen from PineScript)

In PineScript there is a function called valuewhen that returns the n-th most recent occurrence value of a source when a condition is true.在 PineScript 中有一个名为valuewhen的 function ,当条件为真时,它返回源的第 n 个最近出现的值。 So for example, an index of zero will return the most recent value when the condition is true, and an index of one will return the second most recent.因此,例如,当条件为真时,索引为零将返回最近的值,而索引为 1 将返回第二近的值。

How do you do this using Pandas in Python on a Series ?如何在Series上的 Python 中使用 Pandas 来做到这一点? The function signature in PineScript is valuewhen(condition, source, occurrence) → series[float] PineScript 中的 function 签名是 valuewhen valuewhen(condition, source, occurrence) → series[float]

To implement this function, first drop unwanted values using reindex and a condition as a mask.要实现此 function,首先使用重新索引和条件作为掩码删除不需要的值。 Next, shift the series according to which occurrence is desired.接下来,根据需要发生的事件来移动系列。 Then, use reindex to add in the index values that was dropped from the mask and first reindex.然后,使用 reindex 添加从掩码中删除的索引值并首先重新索引。 These index values will point to np.nan .这些索引值将指向np.nan Finally, use ffill() to forward fill values onto the np.nan values.最后,使用ffill()将填充值转发到np.nan值。

This assumes that occurrences is a properly bounded non-negative number, source is an ordered sequence, and the condition is related to the source by their index .这假设occurrences是一个有界的非负数, source是一个有序序列,并且condition通过它们的index与源相关。

This can be written in Python like this:这可以这样写在 Python 中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM