Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
Unni Avatar asked Jul 20 '16 05:07

Unni


People also ask

What is rolling window calculation?

Window Rolling Mean (Moving Average) The moving average calculation creates an updated average value for each row based on the window we specify. The calculation is also called a “rolling mean” because it's calculating an average of values within a specified range for each row as you go along the DataFrame.

What is rolling window in pandas?

Rolling window calculations in Pandas This is the number of observations used for calculating the statistic. Each window will be a fixed size. If its an offset then this will be the time period of each window. Each window will be a variable sized based on the observations included in the time-period.

What does DF Rolling do?

rolling() function provides the feature of rolling window calculations. The concept of rolling window calculation is most primarily used in signal processing and time-series data.

How does Python calculate rolling?

In Python, we can calculate the moving average using . rolling() method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .


1 Answers

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

like image 110
piRSquared Avatar answered Nov 06 '22 05:11

piRSquared