Python如何在数组中加减元素

2024-09-28 05:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个数组,假设:np.array([4,8,-2,9,6,0,3,-6])并且我想将上一个数字添加到下一个元素中,我该怎么做? 每次数字0显示添加元素“restarts”。在

以上面的数组为例,我在运行函数时应该得到以下输出:

如果在事务中插入上述数组,stock = np.array([4,12,10,19,25,0,3,-3])是正确的输出。在

def cumulativeStock(transactions):

    # insert your code here

    return stock

我想不出解决这个问题的方法。任何帮助都将不胜感激。在


Tags: 函数元素yourdefstocknpcode数字
3条回答

另一种矢量化解决方案:

import numpy as np
stock = np.array([4, 8, -2, 9, 6, 0, 3, -6])

breaks = stock == 0
tmp = np.cumsum(stock)
brval = numpy.diff(numpy.concatenate(([0], -tmp[breaks])))
stock[breaks] = brval
np.cumsum(stock)
# array([ 4, 12, 10, 19, 25,  0,  3, -3])

我相信你的意思是这样的?在

z = np.array([4,8,-2,9,6,0,3,-6])
n = z == 0
    [False False False False False  True False False]
res = np.split(z,np.where(n))
    [array([ 4,  8, -2,  9,  6]), array([ 0,  3, -6])] 
res_total = [np.cumsum(x) for x in res]
    [array([ 4, 12, 10, 19, 25]), array([ 0,  3, -3])]
np.concatenate(res_total)
    [ 4 12 10 19 25  0  3 -3]
import numpy as np
stock = np.array([4, 12, 10, 19, 25,  0,  3, -3, 4, 12, 10, 0, 19, 25,  0,  3, -3])

def cumsum_stock(stock):
    ## Detect all Zero's first 
    zero_p = np.where(stock==0)[0]
    ## Create empty array to append final result  
    final_stock = np.empty(shape=[0, len(zero_p)])
    for i in range(len(zero_p)):
        ## First Zero detection
        if(i==0):
             stock_first_part = np.cumsum(stock[:zero_p[0]])
             stock_after_zero_part  = np.cumsum(stock[zero_p[0]:zero_p[i+1]])
             final_stock = np.append(final_stock, stock_first_part)
             final_stock = np.append(final_stock, stock_after_zero_part) 
        ## Last Zero detection
        elif(i==(len(zero_p)-1)):  
             stock_last_part = np.cumsum(stock[zero_p[i]:])
             final_stock = np.append(final_stock, stock_last_part, axis=0)
        ## Intermediate Zero detection
        else:
            intermediate_stock = np.cumsum(stock[zero_p[i]:zero_p[i+1]])
            final_stock = np.append(final_stock, intermediate_stock, axis=0)
    return(final_stock)


final_stock = cumsum_stock(stock).astype(int)

#Output
final_stock
Out[]: array([ 4, 16, 26, ...,  0,  3,  0])

final_stock.tolist()
Out[]: [4, 16, 26, 45, 70, 0, 3, 0, 4, 16, 26, 0, 19, 44, 0, 3, 0]

相关问题 更多 >

    热门问题