I have a large pandas dataframe which contains ids, years, spend values, and a slew of other columns, as shown below:
id year spend .... n_columns
1 2015 321 ... ...
1 2016 342 ... ...
1 2017 843
1 2018 483
2 2015 234
2 2018 321
2 2019 232 ... ...
I am trying to create a new column which classifies the years based on the next years value. Something akin to:
id year spend cat
1 2015 321 increase
1 2016 342 increase
1 2017 843 decrease
1 2018 483 churned #as there is no 2019 data
2 2015 234 churned #as there is no 2016 data
2 2018 321 decreased
2 2019 232 decreased
2 2020 200 nan #max data only goes up to 2020
I have been trying to do this with something like the below, to get the difference between years to determine the category:
def categorize(x):
if math.abs(x['diff']) == x['value']:
return "churned"
elif x['diff'] < 0:
return "decrease"
elif x['diff' > 0:
return "increase"
else:
return None
df = df.sort_values(['id', 'year'], ascending = True)
df['diff'] = df.groupby('id')['spend'].diff(-1)
df = df.apply(categorize, axis = 1)
However, this method and all similar methods seem to fail as there are years missing for some ids (such as id = 2 and year = 2015 above). Is there an easy way to ensure all ids all contain all of the years, even if the values are all zeroed or nulled out? Is there a better way to determine if a year is an increase/decrease/churn than how I am doing it?
Thanks!