0

Apologies in advance, I assume this question was asked but I cannot find quickly. I have around 10 columns with names 'col 1', 'col 2', 'col 3' ... I want to apply the following function on each of them and the output should have base column name + 'avg'.

df['col 1 avg'] = df['col 1'].rolling(5).mean()

I can think of loop throw columns but I don't know how to do it in the easiest way. Thanks for help!

Nata
  • 171
  • 3
  • 15
  • You might want to look [here](https://stackoverflow.com/questions/16353729/how-do-i-use-pandas-apply-function-to-multiple-columns) – yogkm Sep 17 '18 at 23:21

1 Answers1

1

You can get your rolling means for each column using:

df.rolling(5).mean()

Then, you can use add_suffix to add mean to all your column names:

df.rolling(5).mean().add_suffix(' mean')

Finally you can concatenate with your original dataframe using pd.concat. So all in one step:

new_df = pd.concat((df, df.rolling(5).mean().add_suffix(' mean')),axis=1)

Example:

>>> df
   col 0  col 1  col 2
0      1      2      1
1      4      0      0
2      4      2      2
3      4      3      4
4      3      1      0
5      4      2      3
6      2      2      2
7      2      1      0
8      2      2      2
9      2      3      0

>>> new_df = pd.concat((df, df.rolling(5).mean().add_suffix(' mean')),axis=1)

>>> new_df
   col 0  col 1  col 2  col 0 mean  col 1 mean  col 2 mean
0      1      2      1         NaN         NaN         NaN
1      4      0      0         NaN         NaN         NaN
2      4      2      2         NaN         NaN         NaN
3      4      3      4         NaN         NaN         NaN
4      3      1      0         3.2         1.6         1.4
5      4      2      3         3.8         1.6         1.8
6      2      2      2         3.4         2.0         2.2
7      2      1      0         3.0         1.8         1.8
8      2      2      2         2.6         1.6         1.4
9      2      3      0         2.4         2.0         1.4
sacuL
  • 49,704
  • 8
  • 81
  • 106