Calculating Change In Percentage Between Two Numbers (python)
I have a list of prices where I am trying to calculate the change in percentage of each number. I calculated the differences with prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1,
Solution 1:
If you haven't been exposed to the pandas library in Python (http://pandas.pydata.org/), you should definitely check it out.
Doing this is as easy as:
import pandas as pdprices= [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()
Solution 2:
Try this:
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 inzip(prices[::1], prices[1::1]):
print100 * (b - a) / a
Edit: If you want this as a list, you could do this:
print [100 * (b - a) / a for a, b in zip(prices[::1], prices[1::1])]
Solution 3:
Though definitely not the most elegant way, if you'd like to define a function it would look something like this:
def pctc(Q):
output = [0]
for i in range(len(Q)):
if i > 0:
increase = Q[i]-Q[i-1]
percentage = (increase/Q[i]) * 100
output.append(percentage)
return(output)
There's probably even a better way to do that function, but it's clear at least. :))
Post a Comment for "Calculating Change In Percentage Between Two Numbers (python)"