【问题标题】:numpy specific operation on a vectorized basis基于矢量化的 numpy 特定操作
【发布时间】:2020-06-03 11:48:57
【问题描述】:

我有一个以每小时为单位的商店每天的潜在销售数字的数组。

test = np.array([1,2,1,5,3,6,10,0,0,3,2,3,0,0,7,3,6,2,0,0,3,5,4,6])

我的问题是 - 当销售额为 0 时,我们永远不会开店。 - 我们每天只能开两次店(每次连续)

所以我们想要的是计算潜在开业期间的累计潜在销售额。

test = np.array([ 1, 3, 4, 9, 12, 18, 28, 0, 0, 3, 5, 8, 0, 0, 7, 10, 16, 18, 0, 0, 3, 8, 12, 18])

然后我们选择第一个可以获得 28 美元的时期, 以及我们获得 18 美元的最后一个时期。 (如果存在具有相同潜在累积收益的时期,我们选择后者)。

所以我真正想要的是

test = np.array([1,2,1,5,3,6,10,0,0,0,0,0,0,0,0,0,0,0,0,0,3,5,4,6])

现在关闭的时间是 0。

我可以通过这个来完成累积的潜在销售:但我不知道如何进行到最后一步。

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:
    import numpy as np
    
    test = np.array([1,2,1,5,3,6,10,0,0,3,2,3,0,0,7,3,6,2,0,0,3,5,4,6])
    
    sum = 0
    cumulative = []
    for item in test:
        if item != 0:
            sum += item
            cumulative.append(sum)
        else:
            sum = 0
            cumulative.append(0)
    
    max_rev = sorted(cumulative)[-1:]
    index_max = max([i for i, x in enumerate(cumulative) if x == max_rev])
    from_max = index_max
    while cumulative[from_max] != 0: from_max -= 1
    
    next_max_rev = sorted(cumulative[:from_max] + [0]*(index_max-from_max) cumulative[index_max:])[-1:]
    
    index_next_max = max([i for i, x in enumerate(cumulative) if x == next_max_rev])
    from_next_max = index_next_max
    while cumulative[from_next_max] != 0: from_next_max -= 1
    
    for i, x in enumerate(test):
        if ( i > from_max and i <= index_max) or ( i > from_next_max and i <= index_next_max): continue
        else: test[i] = 0
    
    print(test)
    

    返回

    [ 1  3  4  9 12 18 28  0  0  0  0  0  0  0  0  0  0  0  0  0  3  8 12 18]
    

    【讨论】:

    • 非常感谢。如果我想让它变得灵活,我可以选择是否最多可以打开 1 / 2 / 3 次作为输入变量?
    • 而且使用 sorted(cumulative)[-2:] 似乎并不安全 - if test = np.array([1,2,1,5,3,7,10 ,0,0,3,2,3,0,0,7,3,6,2,0,0,3,5,4,6]) 而第二大也在第一个开放时间内。
    • 修复了可能的异常,现在它会在第一个区间之外。
    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 2017-12-10
    • 2017-12-17
    • 2019-03-13
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多