Home > Net >  How can I find out maximum percentage change for n years?
How can I find out maximum percentage change for n years?

Time:06-02

Problem statement: display the maximum percentage change and the year that it occurred. The array looks like this:

import numpy as np
array = np.array([[2010,2011,2012,2013,2014,2015,2016,2017,2018,2019],
                  [1996,2165,2342,2511,2829,3052,3299,3523,3741,3864]])

So what i have tried so far:

compare = np.roll(array,1)
pcdiff = (compare - pcdiff)/compare))

can anyone help with this thank you!

CodePudding user response:

Is that what you're looking for ?

import numpy as np

array = np.array([[2010,2011,2012,2013,2014,2015,2016,2017,2018,2019],
                  [1996,2165,2342,2511,2829,3052,3299,3523,3741,3864]])
values = array[1]
perc_change = [round((values[i]-values[i-1])*100/values[i-1], 2) for i in range(1, len(values))]
max_perc = max(perc_change)

print(max_perc, array[0][perc_change.index(max_perc) 1])

output:

12.66 2014

CodePudding user response:

IIUC, compute the diff, divide by the original data and get the index with argmax (which will be shifted by 1 as diff removes one value):

idx = np.argmax(np.diff(array[1])/array[1, :-1]) 1

array[:, idx]

output:

array([2014, 2829])

Or, if you want the percentage change:

pct_change = np.diff(array[1])/array[1, :-1]
idx = np.argmax(pct_change)

out = (pct_change[idx], array[0, idx 1])

output:

(0.12664277180406214, 2014)

CodePudding user response:

d=dict(zip(array[0],array[1])) # a dictionary with values and years
l=list(d.values())  # a list with values
m=max(((l[x 1]-l[x])/l[x],x) for x in range(len(l)-1))
print(m) #(0.12664277180406214, 3)
position=m[1]
print(m[0],list(d.keys())[position 1])

#output
0.12664277180406214 2014
  • Related