I want to calculate the percentage change either increase or decrease in a list. here is my list ages = [20.3, 30.5, 20.3, 45.5, 50.6, 29.5, 13.4, 140.9]
here is my code
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
How do assign 'new_num' to a new number on the list above and 'old_num' to a previous number on the list above?
Thanks in advance
In Python (as suggested by @sahasrara62 in the comments)
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]
Using 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 * 100 / ages[:-1]
# [ 50.24630542 -33.44262295 124.13793103 11.20879121
# -41.69960474 -54.57627119 951.49253731]
Using 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With