![](/img/trans.png)
[英]How to compute a percentage increase/decrease multiplier in python without if statements
[英]How do i calculate the percentage increase or decrease in a list of values with python
我想计算列表中增加或减少的百分比变化。 这是我的列表年龄 = [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”分配给上面列表中的前一个号码?
提前致谢
在 Python 中(如评论中@sahasrara62 所建议)
ages = [20.3, 30.5, 20.3, 45.5, 50.6, 29.5, 13.4, 140.9]
changes = []
for x1, x2 in zip(ages[:-1], ages[1:]):
try:
pct = (x2 - x1) * 100 / x1
except ZeroDivisionError:
pct = None
changes.append(pct)
# [50.2463054187192,
# -33.44262295081967,
# 124.13793103448275,
# 11.208791208791212,
# -41.699604743083,
# -54.576271186440685,
# 951.4925373134328]
使用 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]
使用 Pandas
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
你可以试试这个:Will get current and next value by index value of list
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
预计 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)
Output:
[0, 50.2463054187192, -33.44262295081967, 124.13793103448273, 11.208791208791212, -41.69960474308301, -54.576271186440685]
计算运行百分比变化的最简单(也是最快)的方法是使用 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)
Output:
[0.0, 50.2, -33.4, 124.1, 11.2, -41.7, -54.6, 951.5]
请注意,如果您除以零,numpy 将自动输入“inf”作为结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.