0

If I have an array, let's say: np.array([4,8,-2,9,6,0,3,-6]) and I would like to add the previous number to the next element, how do I do? And every time the number 0 shows up the addition of elements 'restarts'.

An example with the above array, I should get the following output when I run the function:

stock = np.array([4,12,10,19,25,0,3,-3]) is the right output, if the above array is inserted in transactions.

def cumulativeStock(transactions):

    # insert your code here

    return stock

I can't think of a method to solving this problem. Any help would be very appreciated.

4
  • not sure what you are asking Commented Jun 14, 2017 at 8:02
  • 4
    what about numpy.cumsum? Commented Jun 14, 2017 at 8:02
  • Please show the code that you are using..."And every time the number 0 shows up the addition of elements 'restarts' ". How do you come to this? Anyway, check the Nils Werner answer. I think it is correct. Commented Jun 14, 2017 at 8:08
  • I am not using a code. I have to figure out a code that does this. It is given in the assignment that every time a 0 shows up it "restarts" - just as I showed in the example. Commented Jun 14, 2017 at 8:23

5 Answers 5

2

I believe you mean something like this?

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]
Sign up to request clarification or add additional context in comments.

Comments

0

another vectorized solution:

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])

Comments

0
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]

Comments

0
def cumulativeStock(transactions):

    def accum(x):
        acc=0
        for i in x: 
           if i==0:
              acc=0
           acc+=i
           yield acc

    stock = np.array(list(accum(transactions)))
    return stock

for your input np.array([4,8,-2,9,6,0,3,-6]) it returns array([ 1, 3, 6, 9, 13, 0, 1, 3, 6])

1 Comment

When I run this I do not get any output. I get this message "name 'a' is not defined". But it is this output I would like the function to return though.
-1

I assume you mean you want to seperate the list at every zero?

from itertools import groupby
import numpy


def cumulativeStock(transactions):

#split list on item 0
groupby(transactions, lambda x: x == 0)
all_lists = [list(group) for k, group in groupby(transactions, lambda x: x ==  0) if not k]

# cumulative the items
stock = []
for sep_list in all_lists:
    for item in numpy.cumsum(sep_list):
        stock.append(item)

return stock


print(cumulativeStock([4,8,-2,9,6,0,3,-6]))

Which will return: [4, 12, 10, 19, 25, 3, -3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.