I have a question which has 2 separate numpy arrays respectively.
Year: np.array([2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])
Data: np.array([29057, 30979, 31746, 32964, 31738, 31010,31158,28736,26821,28260])
Is there a way I can display the Years where data has decreased by at least 5% over the previous year.
Eg output: Year where data decreased at least 5%: (2017, 7.77%)
CodePudding user response:
You can do this:
# filter the data elements, this returns an array where some elements are None
l = [year[i] if (data[i]-data[i-1])/data[i-1] < 0.05 else None for i in range(1, len(data))]
# filter out None from the list
l = list(filter(lambda x: x is not None, l))
CodePudding user response:
You can use this code:
import numpy as np
Year = np.array([2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])
Data = np.array([29057, 30979, 31746, 32964, 31738, 31010,31158,28736,26821,28260])
d_years = []
for d1, d2 in enumerate(Data):
if d1 == 0:
prev = d2
else:
percentage = 100 - ((d2 / prev) * 100)
prev = d2
if percentage > 5:
d_years.append(Year[d1])
print('decresed by {p:0.2f}% in {y}'.format(p=percentage, y = Year[d1]))
print(d_years)
CodePudding user response:
For a pure numpy solution, you can use:
pct_change = np.diff(Data)/Data[:-1]
# array([ 0.06614585, 0.02475871, 0.03836704, -0.03719209, -0.0229378 ,
# 0.00477265, -0.07773285, -0.06664115, 0.05365199])
mask = pct_change<-0.05
# array([False, False, False, False, False, False, True, True, False])
np.vstack([Year[1:], Data[1:]])[:, mask]
# array([[ 2017, 2018],
# [28736, 26821]])
pct_change[mask]
# array([-0.07773285, -0.06664115])