【问题标题】:Pandas forward cummax熊猫前锋cummax
【发布时间】:2017-04-20 22:52:02
【问题描述】:

我想在给定一系列价格数据的情况下找出一只股票的最大可能回报。鉴于您只能以未来价格出售,我认为我需要在每一行上放置最高未来价格:

def maxf(idx):
    return prc[idx:].bid.max()

prc['MaxF'] = prc.index.map(lambda x: maxf(x))

此代码确实有效,但它比 pandas.cummax() 花费的时间要长得多。有没有直接的向量方式来编码?

【问题讨论】:

    标签: python pandas numpy lambda


    【解决方案1】:

    forward cummax 是 reverse cummax 的同义词:

    prc.bid[::-1].cummax()[::-1]
    

    【讨论】:

    • 次要:这会反转整个框架,即使我们只打算使用出价列。也许将.bid 向左移动?
    【解决方案2】:

    @Boud 的答案是numpy 版本

    prc.assign(MaxF=np.maximum.accumulate(prc.bid.values[::-1])[::-1])
    

    考虑数据框prc

    np.random.seed([3,1415])
    prc = pd.DataFrame(dict(bid=np.random.rand(10)))
    
    prc
    
            bid
    0  0.444939
    1  0.407554
    2  0.460148
    3  0.465239
    4  0.462691
    5  0.016545
    6  0.850445
    7  0.817744
    8  0.777962
    9  0.757983
    

    然后:

    prc.assign(MaxF=np.maximum.accumulate(prc.bid.values[::-1])[::-1])
    
            bid      MaxF
    0  0.444939  0.850445
    1  0.407554  0.850445
    2  0.460148  0.850445
    3  0.465239  0.850445
    4  0.462691  0.850445
    5  0.016545  0.850445
    6  0.850445  0.850445
    7  0.817744  0.817744
    8  0.777962  0.777962
    9  0.757983  0.757983
    

    对小数据的计时

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 2019-11-28
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多