User defined croston function in Python

Viewed 1569

I want to forecast the intermittent demand values. For that I want the following outputs:

1. non-zero elements values(q)
2. inter arrival time between two non-zero elements(a)

For example, my data is like this [type:series]

1,2,0,0,3,3,0,1,0,0,2,0,0,0,0,4,0,0

and I want output like this and it should be in pandas data frame format.

q  a
1  1
2  1
3  3
3  1
1  2 
2  3
4  4 

I tried some of the codes but I didn't get the proper output.

Can anyone help me to solve this?

1 Answers

IIUC

import pandas as pd
lst = [1,2,0,0,3,3,0,1,0,0,2,0,0,0,0,4,0,0]
s = pd.Series(lst, name='q')

s = s[s!=0].reset_index()
s['a'] = s['index'] - s['index'].shift(1)
s.drop('index', axis=1, inplace=True)

print(s)

# output:

    q     a
0   1   NaN
1   2   1.0
2   3   3.0
3   3   1.0
4   1   2.0
5   2   3.0
6   4   5.0

If you want to fill the NaN with 1 then use s = s.bfill()

Related