简体   繁体   中英

Manually Creating rolling window in pandas

I want to create a function of rolling window that moves through time (example window_size=2 sec) and gives me mean of column 'temp'.

Here is the dataset:

data = { 
  'time': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 
  'temp': [20, 26, 28, 30, 31, 33, 29, 34, 16, 35, 38, 31]
}

The dataset I want

data = {
  'time': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 
  'temp': [20, 26, 28, 30, 31, 33, 29, 34, 16, 35, 38, 31],
  'mean': [23, 27, .....]

I tried the DataFrame.rolling method, but I can only get the mean based on a fixed window size. I need the mean of the column with a flexible window size defined by another column.

Try this:

df_in = pd.DataFrame(data)

df_in['mean'] = df_in['temp'].rolling(2).mean().shift(-1)

Output:

    time  temp  mean
0      1    20  23.0
1      2    26  27.0
2      3    28  29.0
3      4    30  30.5
4      5    31  32.0
5      6    33  31.0
6      7    29  31.5
7      8    34  25.0
8      9    16  25.5
9     10    35  36.5
10    11    38  34.5
11    12    31   NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM