2

I am looking to reverse the effect of numpy's cumsum function, i.e. a cumulative / running total. Looking at the code below I assign a the numbers 1 to 10, and b the running total of those numbers. I need to reverse this process, i.e. calculate a from b. I can code this (see c) but would prefer to use a built in function thats pre-optimised if possible. Is there anything available that fits the bill?

import numpy as np

a = np.arange(1,10)
a
# array([1, 2, 3, 4, 5, 6, 7, 8, 9])

b = np.cumsum(a)
b
# array([ 1,  3,  6, 10, 15, 21, 28, 36, 45], dtype=int32)

c=np.array([b[0]])
c=np.append(c,b[1:9]-b[0:8])
c
# array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)

Many thanks.

Matthew Baker
  • 2,637
  • 4
  • 24
  • 49
  • 3
    `x[1:]-x[:-1]` is the normal way of taking succesive differences. `np.diff` uses it - look at its code. – hpaulj Dec 31 '20 at 09:28

1 Answers1

3

This should help you!

с = b.copy()
с[1:] = np.diff(b)
с
# array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)
AndrosovAS
  • 110
  • 1
  • 1
  • 8