Whats the most pythonic way to calculate percentage changes on a list of numbers

I don't know how large your list of numbers is going to be, but if you are going to process large amounts of numbers, you should have a look at numpy. The side effect is that calculations look a lot simpler.

With numpy, you create an array for your data

>>> import numpy as np
>>> a = np.array([100,105,100,95,100], dtype=float)

and work with arrays as if they were simple numbers

>>> np.diff(a) / a[:-1] * 100.
[ 5.         -4.76190476 -5.          5.26315789]

Here you go:

>>> [100.0 * a1 / a2 - 100 for a1, a2 in zip(a[1:], a)]
[5.0, -4.7619047619047592, -5.0, 5.2631578947368354]

Since you want to compare neighbor elements of a list, you better create a list of pairs you are interested in, like this:

>>> a = range(5)
>>> a
[0, 1, 2, 3, 4]
>>> zip(a, a[1:])
[(0, 1), (1, 2), (2, 3), (3, 4)]

After that it is just a simple math to extract a percentage change from a pair of numbers.


Thanks for the answer guys! A function I implemented based on your answers if someone just wanna copy paste (like me):

def pct_change(nparray):
    pct=np.zeros_like(nparray)
    pct[1:]=np.diff(nparray) / np.abs(nparray[:-1])
    #TODO zero divisionerror
    return pct

Tags:

Python