user11812290
user11812290

Reputation:

I have a list of numbers, and I want to take the difference between the current and previous value

I have a small array and I want to take the difference between the current and previous value, but my array starts with 1. but I don't want 1 - 5 to occur. I want the data set to start and end at the original values:

x = np.array([1,2,3,4,5])


diff = list()
one_year = 1
for i in range(0,len(x)):
    value = x[i] - x[i - one_year] #subtract current year with year before
    #print(x[i-one_year])
    print(value)
    diff.append(value)

print(diff)

-4
1
1
1
1

I want the data to start with 1, not -4. How do I fix this for loop?

Upvotes: 1

Views: 724

Answers (2)

Serial Lazer
Serial Lazer

Reputation: 1669

Try this:

import numpy as np

x = np.array([1,2,3,4,5])

diff = [1]
one_year = 1
for i in range(1,len(x)):
    value = x[i] - x[i - one_year] #subtract current year with year before
    #print(x[i-one_year])
    print(value)
    diff.append(value)

print(diff)

Upvotes: 0

dspr
dspr

Reputation: 2423

You could use this :

x = np.array([1,2,3,4,5])
print(np.diff(x)) #==> 1, 1, 1, 1

Upvotes: 3

Related Questions