Calculating the percentage change between two numbers (Python)

I have a price list where I am trying to calculate the change as a percentage of each number. I calculated the differences with

prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6] def f(): for i in range(len(prices)): print(prices[i]-prices[i-1]) 

Which returns the differences, for example

  2.1 -0.8 -0.5 ... 

I know that the percentage change will be ((ii-1)) / (i-1) * 100, but I don't know how to include it in the script. Any help would be much appreciated.

+8
python
source share
2 answers

Try the following:

 prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6] for a, b in zip(prices[::1], prices[1::1]): print 100 * (b - a) / a 

Edit: If you want this as a list, you can do this:

 print [100 * (b - a) / a for a, b in zip(prices[::1], prices[1::1])] 
+8
source share

If you have not been exposed to the pandas library in Python (http://pandas.pydata.org/), you should definitely check this out.

Doing this is as simple as:

 import pandas as pd prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6] price_series = pd.Series(prices) price_series.pct_change() 
+11
source share

All Articles