[英]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, 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 like返回的差异如下
2.1
-0.8
-0.5
...
I know the change in percentage would be ((i-(i-1))/(i-1) *100, but I don't know how to incorporate that into the script. Any help would be much appreciated.我知道百分比的变化是 ((i-(i-1))/(i-1) *100,但我不知道如何将其合并到脚本中。任何帮助将不胜感激。
If you haven't been exposed to the pandas library in Python (http://pandas.pydata.org/), you should definitely check it out.如果您还没有接触过 Python 中的 pandas 库 (http://pandas.pydata.org/),那么您一定要检查一下。
Doing this is as easy 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()
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 in zip(prices[::1], prices[1::1]):
print 100 * (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])]
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.甚至可能有更好的方法来执行该功能,但至少很清楚。 :)) :))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.