Scott
Scott

Reputation: 79

Loop for Subtracting within Array Elements

I am a newbie using Python and Numpy. I thought this would be simple and probably is. I have an array of times.
For example:

times = (0.5,  0.75,  1.5)

This array will vary in size depending on the files loaded.

I simply want to find the difference in time between each subsequent element.

0.75 - 0.5
then
1.5 - 0.75

and so for the number of elements in the array. Then I put each result into one column.

I have tried various for loops but unable to do it. There must be a simple way?

Thanks, Scott

Upvotes: 2

Views: 4234

Answers (6)

Gregor
Gregor

Reputation: 1

very basic:

liste = [1,3,8]
difference = []
for i in range(len(liste)-1):
    diffs = abs(liste[i] - liste[i+1])
    difference.append(diffs)

print difference

Upvotes: 0

fhtuft
fhtuft

Reputation: 976

this should do it.

import numpy as np


times = np.array([0.5,0.75,1.5,2.0])
diff_times = np.zeros(len(times)-1,dtype =float)

for i in range(1,len(times)):
    diff_times[i-1] = times[i] - times[i-1]

print diff_times

Upvotes: 0

Levon
Levon

Reputation: 143022

diffs = [b-a for a, b in zip(times[:-1], times[1:])]
[0.25, 0.75]

This approach requires no numpy, simple Python. Subtracting

times[1:]
(0.75, 1.5)

times[:-1]
(0.5, 0.75)

from each other

Upvotes: 1

mgilson
mgilson

Reputation: 309929

Or how about these (all variants on the same theme):

import numpy as np
a = np.array([0.5,  0.75,  1.5])
b = a[1:]-a[:-1]
print (b)

or without numpy:

a=[0.5,  0.75,  1.5]
a1=a[1:]
a2=a[:-1]
b=[ aa-a2[i] for i,aa in enumerate(a1) ]

or

a=[0.5,  0.75,  1.5]
c=[x-y for x,y in zip(a[1:],a[:-1])]

Upvotes: 1

abought
abought

Reputation: 2680

First, note that for most everyday uses, you probably won't require an array (which is a special datatype in Numpy). Python's workhorse means of data storage is the list, and is definitely worth reading up on if you're coming from a more rigid programming language. Lists are actually defined using square brackets:

times = [ 0.5,  0.75,  1.5 ]

Then, with special syntax called a list comprehension, we can create a new list that has (length-1) elements. This expression automatically figures out the size of the list needed.

diffs = [ times[i] - times[i-1] for i in range(1, len(times)) ]

And for the sample data provided, returns:

[0.25, 0.75]

Upvotes: 4

Nick Craig-Wood
Nick Craig-Wood

Reputation: 54079

How about this?

>>> import numpy as np
>>> a = np.array([0.5,  0.75,  1.5])
>>> np.diff(a)
array([ 0.25,  0.75])
>>> 

Upvotes: 7

Related Questions