Unni Unni - 2 months ago 10
Python Question

Pandas rolling computations for printing elements in the window

I want to make a series out of the values in a column of pandas dataframe in a sliding window fashion. For instance, if this is my dataframe

state
0 1
1 1
2 1
3 1
4 0
5 0
6 0
7 1
8 4
9 1


for a window size of say 3, I want to get a list as [111, 111, 110, 100, 000...]

I am looking for an efficient way to do this (Of course, trivially I can convert state into a list and then slide the list indices). Is there a way to use pandas rolling computations here? Can I somehow print the elements in a rolling window?

Answer
a = np.array([100, 10, 1])
s.rolling(3).apply(a.dot).apply('{:03.0f}'.format)

0    nan
1    nan
2    111
3    111
4    110
5    100
6    000
7    001
8    014
9    141
Name: state, dtype: object

thx @Alex for reminding me to use dot

Comments