计算两个数字之间的百分比变化(Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12700166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating change in percentage between two numbers (Python)
提问by
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,但我不知道如何将其合并到脚本中。任何帮助将不胜感激。
采纳答案by arshajii
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])]
回答by badgley
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()
回答by Norbert Wesolowski
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. :))
甚至可能有更好的方法来执行该功能,但至少很清楚。:))

