What is the most pythonic way to calculate percentage changes in a list of numbers

I have a list of floating point numbers and I want to generate another list of period returns from my first list.

This is the launch of the mill implementation (not tested - and OBVIOUSLY without error checking / handling):

a = [100,105,100,95,100]

def calc_period_returns(values, period):
    output = []
    startpos, endpos = (period, len(values)-1)

    while True:
        current = values[startpos]
        previous = values[startpos-period]
        ret = 100*((current-previous)/(1.0*previous))
        output.append(ret)
        startpos += period
        if startpos > endpos:
            break
    return output


calc_period_returns(a,1)

# Expected output:
# [5.0, -4.7619047619047619, -5.0, 5.2631578947368416]

Is there a more pythonic way to do this - perhaps using comprehension and list cards?

+5
source share
2 answers

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 neighboring list items, it is better to create a list of pairs of interest to you, for example:

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

After that, it's just simple math to extract the percentage change from a pair of numbers.

+10
source

, , , numpy. , .

numpy

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

,

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

All Articles