如何使用python计算值列表中增加或减少的百分比

如何使用python计算值列表中增加或减少的百分比,python,python-3.x,list,function,Python,Python 3.x,List,Function,我想计算列表中增加或减少的百分比变化。 这是我的名单 年龄=[20.3,30.5,20.3,45.5,50.6,29.5,13.4,140.9] 这是我的密码 def percent_change_in_naira(value): try: for i in value: if old_num > new_num: ((((old_num-new_num)/old_num)*100)) elif old_num == new_

我想计算列表中增加或减少的百分比变化。 这是我的名单 年龄=[20.3,30.5,20.3,45.5,50.6,29.5,13.4,140.9]

这是我的密码

def percent_change_in_naira(value):
  try:
    for i in value:
        if old_num > new_num:
          ((((old_num-new_num)/old_num)*100))
        elif old_num == new_num:
          0
        else:
          ((((new_num-old_num)/old_num)*100))
    return value
  except ZeroDivisionError:
        return 0
如何将“new_num”分配给上面列表中的新数字,将“old_num”分配给上面列表中的前一个数字


提前感谢

您可以尝试这样做:将通过列表的索引值获取当前值和下一个值

def percent_change_in_naira(value):
    output = []
    try:
        for index,i in enumerate(range(len(value))):
            if i == 0:
                output.append(i)
            else:
                old_num = value[index-1]
                new_num = value[index]                    
                output.append(round((((old_num-new_num)/old_num)*100), 3))
    except ZeroDivisionError:
            output.append(0)
    return output
预期产出为:

[0, -50.246, 33.443, -124.138, -11.209, 41.7, 54.576, -951.493]

您可以使用列表:

i = [20.3, 30.5, 20.3, 45.5, 50.6, 29.5, 13.4, 140.9]

i = [0]+[(i[n+1]-i[n])/i[n]*100 if i[n] else 0 for n in range(len(i)-2)]

print(i)
输出:

[0, 50.2463054187192, -33.44262295081967, 124.13793103448273, 11.208791208791212, -41.69960474308301, -54.576271186440685]
[0.0, 50.2, -33.4, 124.1, 11.2, -41.7, -54.6, 951.5]
计算运行百分比变化的最简单(也是最快)方法是使用numpy.array

import numpy as np
li = np.array([20.3, 30.5, 20.3, 45.5, 50.6, 29.5, 13.4, 140.9])

perc=[0.0]+list(np.round((li[1:]/li[:-1]-1)*100,decimals=1))

print(perc)
输出:

[0, 50.2463054187192, -33.44262295081967, 124.13793103448273, 11.208791208791212, -41.69960474308301, -54.576271186440685]
[0.0, 50.2, -33.4, 124.1, 11.2, -41.7, -54.6, 951.5]
请注意,如果您将除法归零,numpy将自动放入'inf'作为结果。

在Python中(如注释中@sahasrara62所建议的)

使用numpy

import numpy as np

ages = np.array([20.3, 30.5, 20.3, 45.5, 50.6, 29.5, 
                 13.4, 140.9])
diff = ages[1:] - ages[:-1]
changes = diff / ages[1:] * 100

# [ 50.24630542 -33.44262295 124.13793103  11.20879121
#  -41.69960474 -54.57627119 951.49253731]
使用熊猫

import pandas as pd

ages = pd.Series([20.3, 30.5, 20.3, 45.5, 50.6, 29.5, 
                  13.4, 140.9])
changes = ages.pct_change() * 100

# 0           NaN
# 1     50.246305
# 2    -33.442623
# 3    124.137931
# 4     11.208791
# 5    -41.699605
# 6    -54.576271
# 7    951.492537
# dtype: float64

您可以添加预期的输出吗?您可以使用zip同时获取两个数值,例如
对于zip中的旧的、新的(值[0:],值[1:])
然后使用您的代码进行处理,看起来您希望您计算绝对百分比变化(即始终为正值)。您能确认吗?这肯定不是最快的,@annzen solution如果比这个快得多,那么对于大型阵列,numpy要比列表理解快得多。是的,对于大型阵列,您的解决方案要快得多