8 python
我有一个价格清单,我试图计算每个数字的百分比变化.我用它来计算差异
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])
Run Code Online (Sandbox Code Playgroud)
返回的差异就像
2.1
-0.8
-0.5
...
Run Code Online (Sandbox Code Playgroud)
我知道百分比的变化将是((i-(i-1))/(i-1)*100,但我不知道如何将其纳入脚本.任何帮助都将非常感激.
bad*_*ley 13
如果您还没有在Python(http://pandas.pydata.org/)中使用pandas库,那么您一定要查看它.
这样做很简单:
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()
Run Code Online (Sandbox Code Playgroud)
ars*_*jii 10
试试这个:
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
Run Code Online (Sandbox Code Playgroud)
编辑:如果您希望将其作为列表,则可以执行以下操作:
print [100 * (b - a) / a for a, b in zip(prices[::1], prices[1::1])]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24194 次 |
| 最近记录: |